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

Node.js+Express中Delete请求无法获取Authorization Header求助

Node.js + Express DELETE接口无法获取Authorization请求头排查

问题背景

基于Node.js和Express开发的后端,90%的接口通过validateToken中间件验证正常,但新增的DELETE接口始终无法获取前端已发送的Authorization请求头,返回错误:

{error: 'Remember to include the Authorization header'}

相关代码

后端代码

  1. CORS配置
// CORS
app.use(cors({
  origin: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
}));
  1. 路由定义
// Routes
router.delete('/package/:id', validateToken, isAdmin, deletePackage);
  1. validateToken中间件
exports.validateToken = async (req, res, next) => {
  try {
    if (!req.headers.authorization) {
      return res.status(401).send({error: 'Remember to include the Authorization header'});
    }
    const token = req.headers.authorization.split(' ')[1];

    const decodedToken = await admin.auth().verifyIdToken(token);

    if (!decodedToken) {
      return res.status(401).send({error: 'Invalid token'});
    }

    req.user = decodedToken.email;

    next();
  } catch (error) {
    return res.status(400).send({error: error});
  }
};

前端请求代码

export const deletePackageApi = id =>
  Request.delete(`/package/${id}`, {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + localStorage.getItem('user-token'),
  });

排查方向及解决方案

1. 修正前端请求头传递格式

多数HTTP客户端(如Axios)的DELETE请求中,请求头需要嵌套在headers字段内,而非直接作为第二个参数的顶层属性。修改前端代码如下:

export const deletePackageApi = id =>
  Request.delete(`/package/${id}`, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('user-token'),
    }
  });

这是最常见的问题——其他请求(如POST/PUT)可能支持直接传头,但DELETE请求的参数结构要求更严格。

2. 确认CORS中间件加载顺序

确保cors中间件在所有路由之前加载,否则路由对应的请求会先被处理,CORS配置无法生效,导致Authorization头被浏览器拦截。

3. 检查路由匹配优先级

确认没有其他同名的DELETE路由定义在当前路由之前。如果存在未添加validateToken中间件的同路径路由,请求会被提前匹配,导致无法进入验证逻辑。

4. 验证token有效性

临时在前端添加日志,确认localStorage.getItem('user-token')返回有效值,避免出现Authorization: Bearer undefined的无效请求头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 13:43:14