Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 865
W.K.S Avatar asked Nov 02 '13 09:11

W.K.S


1 Answers

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');
});
like image 112
Bulkan Avatar answered Oct 11 '22 13:10

Bulkan