Node.js中Auth中间件无法获取Token:MERN栈闪卡应用删除功能报错
MERN栈闪卡应用删除功能授权问题
问题描述
- 基于MERN栈开发的简易闪卡应用,支持添加、编辑、删除闪卡,仅删除卡片功能报错
- 删除功能结构与其他功能一致,但Auth中间件触发了“无Token”错误分支,尽管控制台显示第一个try/catch已成功获取Token
- Postman调用后端删除接口可正常运行,推测问题出在前端请求传递环节
后端Auth中间件代码
const protect = asyncHandler(async (req, res, next) => { let token if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')) { try { //get token from header token = req.headers.authorization.split(' ')[1] //verify token const decoded = jwt.verify(token, process.env.JWT_SECRET) //get user from the token req.user = await User.findById(decoded.id).select('-password') next() } catch (error) { console.log(error) res.status(401) throw new Error('not authorised') } } if (!token) { res.status(401) throw new Error('not authorised, no token') } })
前端相关代码
删除功能Slice代码
//delete user card export const deleteCard = createAsyncThunk( "cards/deleteCard", async (cardData, thunkAPI) => { try { const token = thunkAPI.getState().auth.user.token; return await cardService.deleteCard(cardData, token); } catch (error) { const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); return thunkAPI.rejectWithValue(message); } } );
删除功能Service代码
//delete card const deleteCard = async (cardData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, }; const response = await axios.delete(API_URL, cardData, config); return response.data; };
正常运行的更新功能参考代码
更新功能Slice代码
//slice export const updateCard = createAsyncThunk( "cards/updateCard", async (cardData, thunkAPI) => { try { const token = thunkAPI.getState().auth.user.token; return await cardService.updateCard(cardData, token); } catch (error) { const message = (error.response && error.response.data && error.response.data.message) || error.message || error.toString(); return thunkAPI.rejectWithValue(message); } } );
更新功能Service代码
//service const updateCard = async (cardData, token) => { const config = { headers: { Authorization: `Bearer ${token}`, }, }; const response = await axios.put(API_URL, cardData, config); return response.data; };
关键排查点
- 控制台打印的config、token、cardData均符合预期,但删除请求仍触发无Token错误
- 更新功能与删除功能结构几乎一致,但前者正常运行
内容的提问来源于stack exchange,提问作者Gordon Maloney
相关产品推荐
相关产品推荐

