美文网首页
node - react 跨域问题

node - react 跨域问题

作者: 天往哪方 | 来源:发表于2021-01-12 17:33 被阅读0次
app.all("*", function (req, res, next) {
  // 防止undefined 报错
  if (!req.headers.origin) {
    return
  }
  //设置允许跨域的域名,*代表允许任意域名跨域,如果前端显示不能使用‘*’,则用`request`里的域名代替
  //凡是在header中设置过的参数,必须在Access-Control-Allow-Headers 添加一遍
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header( 'Access-Control-Allow-Credentials','true');
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  res.header('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
  res.header('Access-Control-Allow-Headers',
    'Origin, X-Requested-With,' +
    ' Content-Type,Accept,' +
    'Access-Control-Allow-Origin,' +
    'Access-Control-Allow-Credentials,' +
    'Access-Control-Allow-Methods,' +
    'Access-Control-Allow-Headers')


  if (req.method.toLowerCase() === 'options') {
    res.sendStatus(200);  //让options预验证尝试请求快速结束
  } else {
    next();
  }
})

相关文章

网友评论

      本文标题:node - react 跨域问题

      本文链接:https://www.haomeiwen.com/subject/ppseaktx.html