簡體   English   中英

Express,如何在所有請求的所有路由上設置自定義請求標頭?

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

我有這個節點 API 包裝服務,我需要一次在所有路由/端點上設置 REQUEST 自定義標頭,而不是在每個請求上都這樣做。 我在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);

無論如何我們可以在應用程序級別執行此操作,還是我應該繼續分別在各個路由/請求上設置自定義請求標頭。

假設app = express()並且我們位於服務器根文件的頂部,您可以為所有請求設置這些標頭,如下所示:

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

app.use(customHeadersAppLevel);

我認為Request中沒有set功能。 使用headers屬性設置請求標頭。

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

您還可以使用應用程序級中間件。 像這樣的東西,

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