简体   繁体   English

Express,如何在所有请求的所有路由上设置自定义请求标头?

[英]Express, how to set custom request headers on all routes for all requests?

I have this node API wrapper service, where I need to set REQUEST custom headers on all routes / endpoints at once instead of doing that on each request.我有这个节点 API 包装服务,我需要一次在所有路由/端点上设置 REQUEST 自定义标头,而不是在每个请求上都这样做。 I have tried the following in app.js but receive a not function error: req.set is not a function .我在app.js中尝试过以下操作,但收到一个 not function 错误: req.set is not a function

const customHeadersAppLevel = function (req, res, next) {
  req.set("User-Agent", "zendx/sop API");
  next();
};
app.all("*", customHeadersAppLevel);

Is there anyway we can do this on the app level or should I just go ahead with setting custom request headers on individual routes/requests, respectively.无论如何我们可以在应用程序级别执行此操作,还是我应该继续分别在各个路由/请求上设置自定义请求标头。

Assuming that app = express() and we are at the top of the server's root file, you could set those headers for all your request like this:假设app = express()并且我们位于服务器根文件的顶部,您可以为所有请求设置这些标头,如下所示:

const customHeadersAppLevel = function (req, res, next) {
  req.headers['User-Agent'] = 'zendx/sop API'
  next();
};

app.use(customHeadersAppLevel);

I think there is no set function in Request .我认为Request中没有set功能。 Use headers property to set the request header.使用headers属性设置请求标头。

 const customHeadersAppLevel = function (req, res, next) {
    req.headers['User-Agent'] = 'zendx/sop API';
    next();
 };
 app.all('*', customHeadersAppLevel);

You can also use Application-level middleware.您还可以使用应用程序级中间件。 Something like this , 像这样的东西,

const express = require('express')
const app = express()

app.use((req, res, next) => {
  req.headers['User-Agent'] = 'zendx/sop API';
  next()
})

// Other Route comes here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM