Reputation: 56
I am trying get json data from node.js into angular.js version 1 but i am getting header error like "Failed to load http://127.0.0.1:3000/emps: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
Angular js script code
var myModule = angular.module("myApp",[]).controller("directivesController",function($scope,$http){
var res = $http.get("http://127.0.0.1:3000/emps",{headers:{'Access-Control-Allow-Origin':'*',"Access-Control-Allow-Methods": "*", "Origin":"*", "Access-Control-Allow-Headers": "*"}});
res.success(function(data,status,header,config){
alert("success");
/*console.log(data);
console.log(status);
console.log(header); */
});
res.error(function(data,status,header,config){
/*console.log(data);
console.log(status);
console.log(header); */
alert("error");
});
});
Node.js script code
router.get('/', function(req, res, next) {
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
var jsonObj = JSON.parse(jsonData);
res.send(jsonObj);
});
Upvotes: 1
Views: 244
Reputation: 2376
Set the Access-Control-Allow-Origin header before sending the response,
router.get('/', function(req, res, next) {
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
var jsonObj = JSON.parse(jsonData);
res.setHeader('Access-Control-Allow-Origin','*');
res.send(jsonObj);
});
Upvotes: 0
Reputation: 7187
the issue is cors
to solve it you can use cors module in your nodejs server
var cors = require('cors')
var app = express()
app.use(cors())
Upvotes: 1