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

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

Comments

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);
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.