使用JWT的DELETE接口返回401错误,其余接口正常求排查
嘿,我看到你的问题了——DELETE请求报Uncaught (in promise) Error: Request failed with status code 401,但其他GET/PUT/POST接口都能正常工作,这确实有点让人困惑。咱们一步步来排查和解决:
1. 核心问题:客户端Axios DELETE调用的参数格式错误
Axios的delete方法参数结构是axios.delete(url[, config]),你现在传了三个参数,导致withCredentials: true这个关键配置没有被正确应用——后端拿不到你的认证Cookie,自然会返回401。
修正后的客户端代码:
const deletePost = async (id) => { try { // 把请求数据放在config的data字段里,和withCredentials放在同一个配置对象中 const response = await Axios.delete('http://localhost:5000/api/posts/delpost', { data: { postId: id }, withCredentials: true }) // 简化数据过滤逻辑:直接移除被删除的项 const deleteData = dbdata.filter(item => item._id !== response.data._id) setDBData(deleteData) } catch (err) { console.error('删除操作失败:', err) // 记得捕获错误,方便调试 } }
2. 认证函数的小瑕疵:响应写法无效
原认证函数里return res.sendStatus(401).json(...)是无效的,因为sendStatus会直接发送响应,后面的json方法不会执行。同时建议先检查token是否存在,让逻辑更严谨:
修正后的认证函数:
function JWTAuthenticatToken(req, res, next) { const token = req.cookies.authcookie // 先判断token是否存在 if (!token) { return res.status(401).json({ error: "You have to be logged in!" }) } jwt.verify(token, process.env.JWT_TOKEN_SECRET, (err, userData) => { if (err) return res.status(401).json({ error: "You have to be logged in!" }) req.user = userData next() }) }
3. 后端DELETE路由的两处优化
post.remove()是异步操作,必须加await,否则可能还没完成删除就返回响应;- MongoDB的
_id是ObjectId类型,和字符串request.user.id比较时要转成字符串,避免类型不匹配导致的权限判断错误。
修正后的路由代码:
router.delete('/delpost', JWTAuthenticatToken, async (request, response) => { console.log(request.body) // 现在应该能正确拿到postId了 try { const post = await Post.findOne({ _id: request.body.postId }).populate("postedby", "_id") // 先检查帖子是否存在 if (!post) { return response.status(404).json({ message: "Post not found" }) } // 转成字符串后再比较权限 if (post.postedby._id.toString() === request.user.id) { await post.remove() // 加await确保删除完成 return response.json({ message: "deleted successfully", _id: request.body.postId }) } else { return response.status(403).json({ message: "You are not authorized to delete this post" }) } } catch (error) { console.error('服务器错误:', error) return response.status(500).json({ message: error.message }) } })
核心问题解决后,你的DELETE请求应该就能正常通过认证并执行删除操作了。其他的优化点是为了让代码更健壮、容错性更强。
内容的提问来源于stack exchange,提问作者Nat
相关产品推荐
相关产品推荐

