中间件设置 cors headers 适用于 app.use() 但不适用于特定路由

middleware setting cors headers works with app.use() but not for specific route

中间件:

const enableCors = (req, res, next) => {
  res.set({
    'Access-Control-Allow-Origin': 'http://127.0.0.1:5500',
    'Access-Control-Allow-Headers': 'content-type'
  });
  next();
};
//this works from postman as well as from browser

上面的中间件在像这样添加时工作正常 app.use(enableCors); 但我希望它与特定路由一起工作,我按如下方式使用它:

app.post('/resource', enableCors, (req, res, next)=>{
    res.json({msg:'success'});
});
//this only works from postman

我很确定这与 pre-flight 请求的工作方式有关,因为当邮递员发出请求时,它会以任何一种方式工作。但是当使用 fetch() 从浏览器请求它时,它只适用于 app.use() 这是前端的获取请求:

fetch('http://localhost:3000/resource', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({ key:'value' })
})
.then(res => {
    console.log(res);
})
.catch(err => {
    console.log('something went wrong', err);
    });

是什么阻止它在浏览器请求时使用特定路由?

CORS 在浏览器发送选项 header 时起作用,因此,尝试添加一个新路由器,例如:

app.options('/resource', enableCors, (req, res) => res.send());

Postman 不受 CORS 影响,因为它不是浏览器。