Node.js+React全栈开发API授权报错:未找到授权令牌
问题背景
我用Node.js + React开发应用,后端集成了第三方Instagram爬取API的受保护路由,用Thunder Client携带Bearer Token测试能正常返回数据,但前端React请求该路由时,控制台报错ERROR GET /api/inspiration UnauthorizedError: No authorization token was found。
后端路由代码:
router.get("/inspiration", isAuthenticated, (req, res, next) => { const options = { method: 'GET', url: 'https://instagram130.p.rapidapi.com/account-feed', params: {username: 'lululemon'}, headers: { 'X-RapidAPI-Key': '2b90b0f361msh8b43d50ec02dbcep1952bdjsn487cd58b3f12', 'X-RapidAPI-Host': 'instagram130.p.rapidapi.com' } }; axios .request(options) .then((response) => { console.log("Instagram response", response); res.status(201).json(response.data); }) .catch((err) => { res.status(400).json({ message: "can't get instagram posts!" }); }); });
前端React代码:
import axios from "axios"; const API_URL = "http://localhost:5005"; import React, { useEffect, useState } from "react"; const InspirationPage = () => { const [instagramPosts, setInstagramPosts] = useState([]); useEffect(() => { // Make the API request to get Instagram posts axios .get(`${API_URL}/api/inspiration`) .then((response) => { setInstagramPosts(response.data); console.log("Instagram info:", response.data); }) .catch((error) => { console.error("Error fetching Instagram posts:", error); }); }, []); return ( <div> <h1>Inspiration Page</h1> {instagramPosts ? ( <div> {/* Render Instagram data here */} <p>Username: {instagramPosts.external_url_linkshimmed}</p> {/* Add more fields as needed */} </div> ) : ( <p>Loading Inspiration ...</p> )} </div> ); }; export default InspirationPage;
核心原因
前端请求没有携带后端要求的Bearer Token,而Thunder Client是手动添加了这个token所以请求成功。
解决步骤
- 确保前端已存储授权Token
登录成功后,将后端返回的token存储到localStorage或状态管理工具(如Redux、Context)中,示例:
// 登录成功后保存token localStorage.setItem('authToken', '获取到的Bearer Token值');
- 修改前端Axios请求,携带Authorization头
在请求/api/inspiration时,添加Authorization头,格式为Bearer <你的token>。修改后的前端代码:
import axios from "axios"; import React, { useEffect, useState } from "react"; const API_URL = "http://localhost:5005"; const InspirationPage = () => { const [instagramPosts, setInstagramPosts] = useState([]); useEffect(() => { const fetchPosts = async () => { try { // 从localStorage获取token const authToken = localStorage.getItem('authToken'); if (!authToken) { console.error('未找到授权token,请先登录'); return; } // 携带Authorization头发起请求 const response = await axios.get(`${API_URL}/api/inspiration`, { headers: { 'Authorization': `Bearer ${authToken}` } }); setInstagramPosts(response.data); console.log("Instagram info:", response.data); } catch (error) { console.error("Error fetching Instagram posts:", error); } }; fetchPosts(); }, []); return ( <div> <h1>Inspiration Page</h1> {instagramPosts.length > 0 ? ( <div> <p>Username: {instagramPosts.external_url_linkshimmed}</p> </div> ) : ( <p>Loading Inspiration ...</p> )} </div> ); }; export default InspirationPage;
- 额外检查点
- 确认后端
isAuthenticated中间件是从req.headers.authorization中提取Bearer Token验证的,若中间件逻辑是从其他位置(如query参数)取token,需对应调整前端传参方式。 - 检查token是否过期,过期需重新登录获取新token。
- 若存在跨域问题,后端需配置CORS允许携带
Authorization自定义头。
内容的提问来源于stack exchange,提问作者Simply Alice
相关产品推荐
相关产品推荐

