Reputation: 40064
So I am setting up an app to allow cross domain request. Been using a variety of methods from this post How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js
However I get an error I can't seem to sort out. Here's what I am using (not that I tried about 3 of the methods outlined - they all give the same error).
app.use(function(req, res, next){
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
next();
})
.options('*', function(req, res, next){
res.end();
});
This gives me an error still:
XMLHttpRequest cannot load http://localhost:3000/blah. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
If I comment out the top code I get the expected not allowed error which seems to indicate that the request is properly being handled by that code. I have also retyped the content-type request to ensure that I had not pasted odd characters. Any clues?
Upvotes: 0
Views: 835
Reputation: 416
Use a cors plugin, easier like that and no need to set up the res.header manually
get plugin here: https://github.com/troygoode/node-cors
Example REST API code:
'use strict';
var express = require('express'),
cors = require('cors'),
port = process.env.PORT || 3000,
connect = require('connect'),
app = express();
app.use(connect.bodyParser()); //For POST method JSON form data
//GET method
app.get('/books', cors(), function(req, res){
//send JSON etc
res.json({});
});
//POST method
app.post('/books/', cors(), function(req, res){
var book = req.body;
//insert book to DB etc
//send result back to client
res.send(book);
});
//start server on port 3000
if(!module.parent){
app.listen(port, function(){
console.log('Express server listening on port ' + port + '.');
});
}
Now you can access the REST API from any location, port etc, cheers
Upvotes: 0
Reputation: 81052
You have two Access-Control-Allow-Headers
headers. The last one's going to win.
You probably want one Access-Control-Allow-Headers
header with a value that's a comma-separated list.
Upvotes: 4