我目前有一个NodeJS + ExpressJS作为客户端服务器向后端服务器发出API请求。当我发出API请求时,出现以下错误:
Request header field firstname is not allowed by Access-Control-Allow-Headers in preflight response.
我尝试了一切允许CORS,但我仍然得到同样的错误。以下是我的NodeJS + ExpressJS客户端服务器的设置方式:
var express = require('express');
var cors = require('cors');
var path = require('path');
var config = require('../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = express();
var compiler = webpack(config);
app.use(cors());
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static('./dist'));
app.use('/', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.sendFile(path.resolve('client/index.html'))
})
var port = 3000;
app.listen(port, function(error) {
if (error) throw error;
console.log("Express server listening on port", port);
});
可能是什么问题?目前唯一有效的方法是下载https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en并启用它,然后我就不会收到错误,API请求就会成功。
编辑 - 我如何提出API请求
logInUser(userCredentials) {
var userCredsBody = {
'firstname': `${userCredentials.username}`,
'password': `${userCredentials.password}`
}
var configuration = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(userCredsBody)
}
return function(dispatch) {
fetch('https://serverapi.com:8080/userInfo', configuration)
.then(response => response.json())
.then(response => {
console.log('Successful and ', response)
})
.catch((error) => {
console.log("Error: ", error)
})
}
答案 0 :(得分:1)
更改标题顺序。
使用类似的东西:
var express = require('express');
//This is not longer required, unless you want to disable CORS
//var cors = require('cors');
var path = require('path');
var bodyParser = require('body-parser');
var config = require('../webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var app = express();
var compiler = webpack(config);
//The same, no longer required
//app.use(cors());
app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static('./dist'));
//Add bodyParser to parse all body as JSON
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
function setupCORS(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type,Accept,X-Access-Token,X-Key');
res.header('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
res.status(200).end();
} else {
next();
}
}
app.all('/*', setupCORS);
app.use('/', function (req, res) {
res.sendFile(path.resolve('client/index.html'))
});
var port = 3000;
app.listen(port, function(error) {
if (error) throw error;
console.log("Express server listening on port", port);
});
现在您有一个中间件设置CORS到每个请求。
如果要在单个路径上禁用/启用cors,可能需要更改
app.all('/*', setupCORS);
仅限您要使用CORS配置设置的路由。