Express server and Axios CORS Preflight response is not successful
我有以下使用react.js的get操作(在端口3000上运行)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | 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文件:
1 | "proxy":"http://localhost:3001", |
我尝试在App.js文件中使用不同的标头,并且尝试使用cors库进行此工作等。如何解决此错误?
谢谢!
我找到了解决方案。 问题1.我确实必须从前端删除标头。 第二个也是最重要的一点是,当您使用代理进行axios调用时,您不应这样做:
axios.get(api_url + '/schools/countries/' + country)
你应该做这个:
1 | axios.get('/schools/countries/' + country) |
没有本地主机部分。