I am developing a REST web service in Node.JS for working with a basic framework. I defined a Person model with urlRoot: http://localhost:3000/usersand I created a request handler that adds a person to the database when receiving a mail 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 the other responses that the addition of headers: Access-Control-Allow-Origin:*and Access-Control-Allow-Methods:GET,PUT,POST,DELETEsolve the problem, but it did not work for me. I also tried putting these headers in a .htaccess file, but no luck.
Can someone tell me if something is wrong with the code or some solution to this problem?
source
share