解决 express 框架跨域问题

使用 express 框架生成 node 服务器,作为后台服务器,解决跨域请求方式如下:

在 app.js 文件中添加如下代码,即可解决跨域问题

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

//或者

app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  //设置仅接受 application/json 格式请求
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

猜你喜欢

转载自blog.csdn.net/yun_hou/article/details/87623580
今日推荐