节点服务器无法检索反应axios请求标头参数的值
我需要访问服务器端(Node)中的axios标头授权令牌,显示未定义。请帮助..节点服务器无法检索反应axios请求标头参数的值
客户端(反应)要求:
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' }
如何获取授权令牌值?
谢谢。
我假设你使用快递。如果是这样,请不要将标头值设为req.headers.authorization
,请尝试req.get('authorization')
。
不工作,console.log(req.header('authorization'));仍然显示未定义。 –
您使用哪种版本的快递? – mersocarlin
版本:[email protected] –
如果你是一个跨源的HTTP请求,请确保CORS已经在服务器中启用。如果您使用快递cors中间件可以使用。
我想你的问题在于,因为CORS尚未启用,你的服务器将首先收到一个OPTIONS请求,所以你的控制台的整个头是来自OPTIONS请求,而不是你想要的GET请求。您可以使用console.log(req.method)
进行验证。 BTW req.headers.authorization
可以接收标题。
console.log(req.method);显示“选项”和req.headers.authorization仍未定义。 –
您是否在服务器上启用了CORS? – movier
是的,这是我的本地主机。我设置了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 (); }); –
[如何从请求中使用NodeJS连接提取请求http头]可能的重复(https://stackoverflow.com/questions/13147693/how-to-extract-request-http-headers-from-a-request -using-nodejs-connect) – mersocarlin