【问题标题】:Node server unable to retrive the value of react axios request header parameter节点服务器无法检索反应 axios 请求标头参数的值
【发布时间】:2018-03-06 14:23:22
【问题描述】:

我需要在服务器端(节点)访问 axios 标头授权令牌,显示未定义。请帮忙..

客户端(React)请求:

var config = {
        headers: {
            'cache-control':'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
            'authorization' :'bearer '+Auth.getToken()
          }
      };
    axios.get(ApiConfig.API_BASE+'api/admin/profile/', config).then(function(response) {
      this.setState({status:'success', profile: response.data.data});
    }).catch(function(response) {
        console.log(response);
    });

服务器端(节点):

module.exports = (req, res, next) => {

console.log(req.headers.authorization); 

  if(!req.headers.authorization) {
    return res.status(401).end();
  }
 }; 

日志显示未定义。我也控制台整个标题,但他们的输出是:

{ host: 'localhost:8027',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  'access-control-request-method': 'GET',
  'access-control-request-headers': 'authorization,cache-control',
  origin: 'http://localhost:3001',
  connection: 'keep-alive' }

如何检索授权令牌值?

谢谢。

【问题讨论】:

标签: node.js reactjs http-headers axios


【解决方案1】:

如果您正在发出跨域 HTTP 请求,请确保您的服务器中已启用 CORS。如果你使用 express cors 中间件可以使用。

我想您的问题是,由于尚未启用 CORS,您的服务器将首先收到 OPTIONS 请求,因此您控制台的整个标头来自 OPTIONS 请求,而不是您想要的 GET 请求。您可以使用console.log(req.method) 进行验证。 BTW req.headers.authorization 可以接收标头。

【讨论】:

  • console.log(req.method);显示“选项”和 req.headers.authorization 仍未定义。
  • 您是否在服务器上启用了 CORS?
  • 是的,这是我的本地主机。我设置 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept, Authorization"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); next(); } );
【解决方案2】:

我假设您使用的是 express。如果是这样,请尝试req.get('authorization'),而不是将标头值设为req.headers.authorization

http://expressjs.com/en/api.html#req.get

【讨论】:

  • 不工作,console.log(req.header('authorization'));仍然显示未定义。
  • 您使用的是哪个版本的 express?
  • 版本:express@4.15.4
  • @PriyabrataAtha 我已经更新了答案。请再次检查
猜你喜欢
  • 1970-01-01
  • 2015-05-16
  • 2020-09-12
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 2022-07-06
  • 2021-10-06
相关资源
最近更新 更多