1252748 1252748 - 1 year ago 76
Javascript Question

Express enabling CORs headers still cause errors

Using the code provided by http://enable-cors.org/ for express I've added to my index.js file

/*these first five line direct from http://enable-cors.org/.com*/
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

var PORT = 3333;
app.listen(PORT, function(){
console.log('listening on port', PORT);

request({url: 'http://bl.ocks.org/mbostock/raw/4090846/us.json', json: true}, function(err, data){
app.get('/us', function(req, res, next){
console.log(req) //prints correctly

localhost:3333/us shows the json correctly, but making a request from localhost:3000 (a port being served by browsersync) fails with the error

d3.min.js:1XMLHttpRequest cannot load localhost:3333/us. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Is this no longer the correct way to enable CORS for localhost on express? I've also tried passing the
as its first argument but no luck.

Answer Source

When making an Ajax call, you need a fully qualified URL with the protocol in it. This is not a legal URL:


It is something you can type in the browser and the browser will automatically add a protocol to it (the browser does all sorts of things to try to make what you type in the URl bar into a legal URL, but that logic does not happen for requests made via Javascript and Ajax). Instead, change the URL to:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download