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

Node.js Express API生产环境(Nginx部署)auth_token header获取为undefined

解决Nginx部署后无法获取auth_token请求头的问题

这个问题的核心原因是Nginx默认会忽略包含下划线的HTTP请求头——HTTP标准推荐头名称使用连字符(-)而非下划线(_),Nginx默认配置underscores_in_headers为off,会自动过滤掉带下划线的请求头,导致后端拿不到值。本地环境没有Nginx代理,所以请求头能正常传递。

下面提供两种解决方案:

方案一:修改Nginx配置,允许带下划线的请求头

在Nginx的server配置块中添加underscores_in_headers on;指令,同时确保代理时传递该请求头:

server {
  listen 80;
  server_name your-domain.com;

  # 开启允许下划线请求头
  underscores_in_headers on;

  location / {
    proxy_pass http://your-node-app:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # 显式传递auth_token头(可选,但确保万无一失)
    proxy_set_header auth_token $http_auth_token;
  }
}

修改完成后,重启Nginx服务:

sudo nginx -s reload

方案二:修改请求头名称为符合HTTP规范的格式

将请求头从auth_token改为auth-token(用连字符替代下划线),同时更新后端中间件的获取逻辑:

修改后的认证中间件代码:

const authMiddleware = (req, res, next) => {
  const token = req.header("auth-token");
  console.log(req.header('auth-token'));

  if (!token) {
    return res.status(401).json({ message: "No token, authorization denied" });
  } else {
    // 这里继续你的token验证逻辑
    next();
  }
};

同时需要确保前端发送请求时,使用auth-token作为头名称,这样既符合HTTP标准,也能避免Nginx的过滤问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:52:36