Express服务器和Axios CORS Preflight响应不成功

时间:2017-10-12 21:44:55

标签: javascript node.js reactjs express cors

我使用react.js(在端口3000上运行)进行以下get操作

var config = {
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
    // 'Accept': 'application/json',
    // 'Content-Type': 'application/json',
  }
};
axios.get(api_url + '/schools/countries/' + country, config)
  .catch(err => {
    alert('There was an error trying to fetch', country)
  })
  .then(response => {
    .....

}

我正在使用代理将其发送到在端口3001上运行的快速服务器。快速服务器中的App.js文件如下:

var express = require('express');
var app = express();
var cors = require('cors')
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));

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

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'URLs to trust of allow');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  if ('OPTIONS' == req.method) {
    res.sendStatus(200);
  } else {
    next();
  }
});


//app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
app.use('/schools', schools);

console.log("IN APP.JS");
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

由于某种原因,我收到以下错误:

[错误]无法加载资源:预检响应不成功(MR,第0行)

[错误] XMLHttpRequest无法加载http://localhost:3000/schools/countries/MR。飞行前响应不成功

在反应方(前端)我有这是package.json文件:

"proxy": "http://localhost:3001",

我尝试在App.js文件中使用不同的标题,我尝试使用cors库来完成这项工作等。如何修复此错误?

谢谢!

1 个答案:

答案 0 :(得分:-1)

我找到了解决方案。问题1.我必须从前端删除标题。第二个也许是最重要的是,当你使用代理进行axios调用时你应该不这样做:

var api_url= "http:localhost" axios.get(api_url + '/schools/countries/' + country)

你应该这样做:

axios.get('/schools/countries/' + country)

没有localhost部分。