我使用的是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));
})
我哪里做错了?
尝试使用res.append(name,value)
代替res.set(name,value)
。
app.use((req, res, next) => {
res.append('My-header', 'some value');
next();
})
或者你可以使用cors中间件
让我知道这是否有效
假设我们有一些像
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);
他们的自定义头必须在你的路由之前