我有这个代码:
app.use((req,res,next)=> { res.header(‘Access-Control-Allow-Origin’,’*’); res.header(‘Access-Control-Allow-Methods’,‘PUT,GET,DELETE,POST,OPTIONS’); res.header(” …
很难发现错误......
但我发现它......
问题是,对于每个请求,我得到两个,因为 的 飞行前请求 强> 在进行跨源请求时使用方法OPTIONS。
所以我补充道
app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Authorization, X-Requested-With'); //END when options... so the request can continue. if (req.method === 'OPTIONS') { return res.status(200).end(); } next(); });
或者如果愿意,请表达支持app.METHOD,包括选项...所以你可以
app.options("/*", function(req, res, next){ res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Authorization, X-Requested-With'); res.send(200); });
现在工作正常!...
(很多小时都在寻找这个问题。)
有更好的解决方案吗?