You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/后端学习者遇Axios JsonWebTokenError:JWT未提供问题求助

问题:删除博客时JWT请求头未正确携带导致500错误

我是React/后端学习者,尝试删除一篇需要携带JWT请求头的博客文章,Insomnia测试完全正常,但自己的应用中始终报错,找不到问题所在。


前端代码

App.jsx

const handleRemove = async (id) => {
    const data = await JSON.parse(window.localStorage.getItem('username'));
    loginServices.setToken(data)
    await loginServices.removeBlog({
      id: id,
    })
    setUpdate(Math.floor(Math.random() * 100));
  }

loginServices.jsx

let token = '';
  
  const setToken = (newToken) => {
    console.log(newToken.token)
    token = `bearer ${newToken.token}`;
  }

  const removeBlog = async (blog) => {

     const config = {
     header: {Authorization: token},
      }

  console.log(blog.id);

  const response = await axios.delete(`${URI}/api/blog/${blog.id}`, config);
  }

后端代码(blogs.js)

const deleteBlog = async (req, res) => {

        const token = req.token

        const decodedToken = jwt.verify(token, process.env.SECRET);


        if(!token || !decodedToken.id) {
                return res.status(400).json({error: 'token or wrong user'});
        }

        const blogId = req.params.id;
        const blog = await BlogSchema.findById(blogId);
        

        if(blog.userId.toString() === decodedToken.id) {
                await BlogSchema.deleteOne({_id: blogId})
                return res.status(204).json({ message: 'Blog Deleted'}).end();
        }

};

错误信息

JsonWebTokenError: jwt must be provided

xhr.js:220          DELETE http://localhost:3001/api/blog/630244cc261924f7a0b542cb 500 (Internal Server Error)
dispatchXhrRequest @ xhr.js:220
xhrAdapter @ xhr.js:16
dispatchRequest @ dispatchRequest.js:58
request @ Axios.js:109
Axios.<computed> @ Axios.js:131
wrap @ bind.js:9
removeBlog @ Login.jsx:46
handleRemove @ App.jsx:87
await in handleRemove (async)
onClick @ RenderData.jsx:38
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
App.jsx:91 Uncaught (in promise) AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}

控制台日志(确认传入setToken的数据有效)

{token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZ…Q4M30.b6oPD9KmAEm7joU45V5WAw0eacWW22oV19Pg0hpmOS0', username: 'sara', name: 'Saraza'}
Login.jsx:8 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImhkaXRhbm8iLCJpZCI6IjYyZmFmNjBhOWZmODA4ODZmNWVhNWMyOSIsImlhdCI6MTY2MTIyMzQ4M30.b6oPD9KmAEm7joU45V5WAw0eacWW22oV19Pg0hpmOS0

解决方案

问题出在Axios请求配置的字段拼写错误:你把请求头的配置字段写成了单数header,但Axios要求的是复数headers,导致Authorization头没有被正确携带到后端。

修改loginServices.jsx中的config部分:

const config = {
  headers: {Authorization: token}, // 将header改为headers
}

修改后,Axios会正确把Authorization请求头发送到后端,后端就能拿到JWT进行验证,删除操作即可正常执行。


内容的提问来源于stack exchange,提问作者user9561062

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 14:15:13