Reputation: 7575
I currently have a NodeJS + ExpressJS as a client-server making API requests to a back-end server. When I make an API request, I get the following error:
Request header field firstname is not allowed by Access-Control-Allow-Headers in preflight response.
I tried everything to allow CORS but I am still getting the same error. Here is how my NodeJS + ExpressJS client-server is set up as:
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);
});
What may be the issue? The only way that currently works is by downloading https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en and enabling it, then I would not get the error and API request would be successful.
EDIT - How I am making the API request
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)
})
}
Upvotes: 2
Views: 5789
Reputation: 1250
Change the headers order.
Use something like this:
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);
});
Now you have a middleware setting CORS to each request.
If you want to disable/enable cors, on a single route, perhaps you need to change the
app.all('/*', setupCORS);
to only the routes you want to setup with a CORS configuration.
I added a body-parser middleware.
Upvotes: 4