我正在尝试从node.js获取json数据到angular.js版本1,但我收到标题错误,如“无法加载http://127.0.0.1:3000/emps:对预检请求的响应未通过访问控制检查:否”所请求的资源上存在Access-Control-Allow-Origin'标头。因此不允许原点'null'访问。“
Angular js脚本代码
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脚本代码
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);
});
答案 0 :(得分:1)
答案 1 :(得分:0)
在发送响应之前设置Access-Control-Allow-Origin标头
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);
});