chetan.mohol
chetan.mohol

Reputation: 56

Fetching json from node.js in angular.js 1

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

Answers (2)

vibhor1997a
vibhor1997a

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

Fadi Abo Msalam
Fadi Abo Msalam

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

Related Questions