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);
});
  • 2
    Possible duplicate of [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – str Dec 12 '17 at 09:34
  • you have to set the header on the server side not on the client side – vibhor1997a Dec 12 '17 at 09:37

2 Answers2

1

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())
Fadi Abo Msalam
  • 6,739
  • 2
  • 20
  • 25
0

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);
  });
vibhor1997a
  • 2,336
  • 2
  • 17
  • 37