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

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?

+4
source share
2

express, cors, CORS, ,

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

app.use(cors());

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

OPTIONS HTTP. CORS -:

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
+7

All Articles