express解决跨域问题

2020-04-24  本文已影响0人  我有一条小黑狗
req.headers.origin为动态设置

Access-Control-Allow-Origin如果设置为‘*’,可能会报

设置为*

所以需要动态设置Access-Control-Allow-Origin

动态设置

//设置跨域访问

app.all('*', function(req, res, next) {

  res.header("Access-Control-Allow-Origin", req.headers.origin);

  res.header("Access-Control-Allow-Credentials", "true");

  res.header("Access-Control-Allow-Headers", "*");

  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");

  res.header("X-Powered-By",' 3.2.1');

  if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/

  else next();

});

上一篇 下一篇

猜你喜欢

热点阅读