最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Express, how to set custom request headers on all routes for all requests? - Stack Overflow

programmeradmin0浏览0评论

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. I have tried the following in app.js but receive a not function error: 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.

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. I have tried the following in app.js but receive a not function error: 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.

Share Improve this question edited Jun 1, 2022 at 8:06 Youssouf Oumar 46.6k16 gold badges103 silver badges105 bronze badges asked May 31, 2022 at 16:36 ZeusoxZeusox 8,47810 gold badges36 silver badges64 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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:

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. Use headers property to set the request header.

 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 es here

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论