0
我已經使用react.js以下取得動作Express服務器和愛可信CORS預檢響應不成功
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 => {
.....
}
(3000端口運行),我使用的是代理髮送到Express服務器在端口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;
,由於某種原因,我得到以下錯誤:
[錯誤]無法加載資源:Prefli ght響應不成功(MR,第0行)
[錯誤] XMLHttpRequest無法加載http://localhost:3000/schools/countries/MR。預檢響應不成功
在反應側(前端)我有這樣的的package.json文件:
"proxy": "http://localhost:3001",
我已經在App.js文件,我使用不同的報頭試圖已嘗試使用Cors庫來完成這項工作等。我該如何解決這個錯誤?
謝謝!
刪除'header:'訪問控制 - 允許來源':'*', '訪問控制允許標題':'來源,X請求,內容類型,接受' , }'來自您的前端代碼。這些頭文件是服務器發送的* response *頭文件。將它們添加爲請求標頭的唯一效果是以幾乎所有的方式來分解事物。 – sideshowbarker
當我這樣做時,我得到這些錯誤:[錯誤]來源http://123.45.67.89:3000是Access-Control-Allow-Origin不允許的。 [錯誤]無法加載資源:原始http://123.45.67.89:3000不被Access-Control-Allow-Origin允許。 (MR,line 0) [錯誤]由於訪問控制檢查,XMLHttpRequest無法加載http:// localhost:3000/schools/countries/MR。 – 39fredy