Im am pulling my hair since days with this issue. I have build a restfull api ussing nodejs to serve json data to an angularjs frontend. I have tested my api with Postdam chrome extension and it works and ussing it with a mobile app that I am building it works too. The issue is with angular.
When I try to call an endpoint from angujar it fire this error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://188.166.68.124' is therefore not allowed access. The response had HTTP status code 400.
NodeJS config
var express = require('express');
var app = express();
....
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers');
next();
});
One of my endpoints
router.route("/user/login")
.post(function(req,res){
var username = req.body.username;
var password = req.body.password;
... username and password comprobation and cleaning....
User.findOne({username: username},function(err,user){
if (err) res.send(err)
console.log(user);
if (user != null){
if (user.password == password)
res.send(user);
}
else{
res.send(403);
}
}
else{
res.send(403);
}
});
}
});
AngularFunction
this.login = function(user,password){
var datatoLogin = {"username":user,"password":password};
console.log("login function");
$http({
method:'POST',
data: $.param(datatoLogin),
headers:{'Access-Control-Allow-Origin': '*'}, // removing this has no effect
url: 'http://188.166.68.124:8080/api/user/login'
//withCredentials : true
}).success(function(data, status, headers, config){
console.log(data);
this.auth = true
//get data from data...
}).error(function(data,status,headers,config){
console.log("error getted");
console.log(data);
});
}
Can you please guys give me a hand on this?
Try this:
this.login = function(user,password){
var datatoLogin = {"username":user,"password":password};
console.log("login function");
$http({
method:'POST',
data: $.param(datatoLogin),
headers:{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}, // removing this has no effect
url: 'http://188.166.68.124:8080/api/user/login'
//withCredentials : true
}).success(function(data, status, headers, config){
console.log(data);
this.auth = true
//get data from data...
}).error(function(data,status,headers,config){
console.log("error getted");
console.log(data);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With