首页 > 解决方案 > 无法在 express 中设置响应标头

问题描述

我无法设置我的标题有什么问题?

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

app.get('/', (req,res)=>{
  res.header('myHeader','ok');
   /*
   even
   res.set('myHeader','ok');
   tried but there is no difference
   */
  res.redirect('/x');
  })

app.get('/x',(req,res)=>{
  res.send(req.headers);
  })

app.listen(3000);

当我导航到时,localhost:3000每次都会得到相同的结果。

这是结果:

{
host: "localhost:3000",
connection: "keep-alive",
upgrade-insecure-requests: "1",
user-agent: "XX",
accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
accept-encoding: "gzip, deflate, br",
accept-language: "en-US,en;q=0.9",
cookie: "XX"
}

如您所见myHeader,它没有出现在列表中。

标签: node.jsexpressheader

解决方案


好的,这就是解决方案,当我们进行重定向时,实际上我们正在发出一个新的 http 请求。所以在我的情况下,路径req中使用的/x路径与路径不同/


推荐阅读