无法查看授权标头

时间:2020-08-03 09:11:41

标签: node.js http webserver

我使用的是node.js默认的HTTP模块,并且具有 HTTP网络服务器

我使用request.headers获取所有标头,但是当我尝试执行request.headers.authorization时,它返回未定义,但是存在授权as you can see here.

我尝试执行JSON.parse(request.headers).authorization,但仍未定义,并且崩溃了。如何获得授权标头内容?

1 个答案:

答案 0 :(得分:0)

也许您可以使用方法request.getHeader(name) 我看着https://nodejs.org/api/http.html#http_request_getheader_name

编辑1:

index.js

const http = require('http');

const server = http.createServer((request, response) => {
  console.log(request.headers);
  console.log(request.headers.authorization);
  console.log('----');

  const headers = {
    'Content-Type': 'text/plain',
  };
  let statusCode = 404;
  response.writeHead(200, headers);
  response.end('Hi');
});

server.listen(8080, () => {
 console.log(`Server listening on port :8080 ?`);
});

在第一航站楼执行:

node index.js

第二号航站楼:

curl localhost:8080 -H 'authorization: hello'

第一终端的输出是:

{ host: 'localhost:8080',
  'user-agent': 'curl/7.68.0',
  accept: '*/*',
  authorization: 'hello' }
hello
----