nodejs搭建服务器跨域设置 cc趣味屋

nodejs搭建服务器跨域设置
发表于:2021-04-15 分类:技术 评论:0 阅读:2267

前端vue在axios配置了

axios.defaults.withCredentials = true;

的情况下,

后端nodejs 路由配置跨域只能写一个域名,无法使用*号.否则会报错

router.all('*'function(reqresnext) {
    res.header('Access-Control-Allow-Origin''http://127.0.0.1:8081')
    res.header('Access-Control-Allow-Headers''*')
    res.header("Access-Control-Allow-Credentials"true);
    res.header('Content-Type''application/json;charset=utf-8')
    next()
})

若想写*号,允许所有域名请求

router.all("*",function(req,res,next){
  //设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin","*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers","content-type");
  //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == 'options')
      res.send(200);  //让options尝试请求快速结束
  else
      next();
})

则vue的axios 这句必须注释掉 否则会报错

// axios.defaults.withCredentials = true;
暂无评论