【问题标题】:How to get read headers in node.js using body-parser?如何使用 body-parser 在 node.js 中读取标头?
【发布时间】:2017-04-05 04:05:21
【问题描述】:

我正在尝试使用node.jsexpress4body-parser 创建一个演示 API 服务器。我正在尝试使用一些Api-Key 来保护它,这些Api-Key 必须在请求标头中传递。但是,我做不到。

我试过了

console.log(bodyParser.getheader("Api-Key"))

console.log(app.getheader("Api-Key"))

但在这两种情况下我都会收到错误

getheader is not a function

那么现在我可以使用正文解析器读取标题了吗?

【问题讨论】:

    标签: node.js http-headers body-parser get-headers


    【解决方案1】:

    没有.getHeader()。要获取请求的标头,请使用req.get()(或其别名req.header())。例如:

    var app = express()
    
    app.use(function (req, res, next) {
      console.log(req.get('Api-Key'))
      next()
    })
    

    更多信息请参见the Express 4 docs for req

    【讨论】:

    • 但是我必须在所有请求中都这样做,我想在一个共同的地方这样做,如果失败,不要继续前进
    • 如果你想让一个中间件为每个请求执行,不要提供路由。 (我已经更新了答案以显示这一点。)
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    相关资源
    最近更新 更多