【问题标题】:How to set custom header correctly in Node Express?如何在 Node Express 中正确设置自定义标头?
【发布时间】:2021-09-01 05:31:13
【问题描述】:

我使用的是 Node Express 4.17。

我想使用中间件来添加自定义标头。

app.use((req, res, next) => {
  res.set('My-header', 'some value');
  next();
})

但我无法在路由器中获取它。

它甚至不存在于标题中。

app.get('/abc', (req, res) => {
  console.log(req.headers['My-headers']);
  console.log(Object.keys(req.headers));
})

我在这里做错了什么?

【问题讨论】:

    标签: node.js express middleware


    【解决方案1】:

    尝试使用res.append(name,value) 而不是res.set(name,value)

    app.use((req, res, next) => {
      res.append('My-header', 'some value');
      next();
    })
    

    或者您可以使用cors 中间件。

    让我知道这是否有效

    【讨论】:

      【解决方案2】:

      假设我们有一些类似的

      function headers (req: Request, res: Response, next: NextFunction) {
          res.header("Access-Control-Allow-Origin", "http://localhost:3000");
          res.header("Access-Control-Allow-Credentials", "true");
          res.header("Access-Control-Allow-Methods", "OPTIONS,HEAD,GET,PUT,POST,PATCH");
          res.header("Accept-Language", "es, en");
          res.header(
              "Content-Security-Policy",
              "default-src 'self'; base-uri: 'self'; strict-dynamic 'self'; manifest-src 'self'; script-src 'self'; style-src 'self'"
          );
          res.header(
              "Access-Control-Allow-Headers",
              "Origin, Csrf-Token, Accept-Language, Content-Type, Accept, Range, X-Ahoritagram-Mime, X-Ahoritagram-Type, X-Ahoritagram-User, X-Ahoritagram-Auth, X-Ahoritagram-License, X-Ahoritagram-Size, X-Ahoritagram-Platform, X-Ahoritagram-ProductSub"
          );
      
          next();
      }
      

      后来我们有一些类似的

      const app = express();
      app.use(headers);
      

      它们的自定义标头必须在您的路线之前

      【讨论】:

        猜你喜欢
        • 2016-07-07
        • 2013-03-05
        • 2015-09-06
        • 2021-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-03
        相关资源
        最近更新 更多