Origin http://localhost is not allowed by Access-Control-Allow-Origin.

10,226

Solution 1

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

Solution 2

You need to implement a response when using the same path with the OPTIONS HTTP method. I have this code for allowing CORS in a whole express app:

var app = express()
app.use(function(req, res, next) {
    if (req.headers.origin) {
        res.header('Access-Control-Allow-Origin', '*')
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization')
        res.header('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE')
        if (req.method === 'OPTIONS') return res.send(200)
    }
    next()
})
// configure your routes
Share:
10,226
W.K.S
Author by

W.K.S

#SOreadytohelp

Updated on June 25, 2022

Comments

  • W.K.S
    W.K.S almost 2 years

    I'm developing a REST webservice in Node.JS to work with the backbone framework. I've defined a Person model with urlRoot: http://localhost:3000/users and I've created a request handler which adds the person to a database on receiving a post request.

    app.post('/users', user.add(db));

    exports.add = function(db){
        return function(req,res){
    
            console.log(req.body);
    
            var name = req.body.name;
            var age = req.body.age;
            var sex = req.body.sex;
            var job = req.body.job;
    
            var peopleDb = db.get('people');
    
            peopleDb.insert({
                'name':name,
                'age':age,
                'sex':sex,
                'job':job
            },function(e,docs){
                if(e){
                    console.log(e);
                }else
                {
                    res.setHeader('Content-Type','application/json');
                    res.setHeader('Access-Control-Allow-Origin','*');
                    res.setHeader('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
                    res.writeHead(200);
                    res.end(JSON.stringify(docs));
                }
            });
        }
    }
    

    When I try to execute the code, I get this in the console:

    Origin http://localhost is not allowed by Access-Control-Allow-Origin.

    I read from other answers that adding the headers:Access-Control-Allow-Origin:* and Access-Control-Allow-Methods:GET,PUT,POST,DELETE would solve the problem but it hasn't worked for me. I have also tried putting these headers in an .htaccess file but no luck.

    Can someone tell me if there's something wrong with the code or any solution to this problem?