【发布时间】:2016-05-12 13:17:45
【问题描述】:
我有以下用 Node js 编写的服务。通过浏览器单独访问时,该服务运行良好。
var http = require('http');
const PORT=8124;
var server = http.createServer(function (request, res){
//res.setHeader(Access-Control-Allow-Origin, *);
var json = JSON.stringify({
id : 1,
message : 'Hurray it worked'
});
res.end(json);
});
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
我正在从下面的离子应用程序调用上述服务。
angular.module('starter.controllers', [])
.controller('LoginCtrl', function($scope, $http) {
$scope.data = {};
$scope.login = function() {
$http.post("http://localhost:8124")
.success(function(data){
alert("Success");
})
.error(function (error){
alert(error);
});
}
})
我在运行应用程序时收到以下错误。
跨域请求被阻止:同源策略不允许读取位于http://localhost:8124/ 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)
为了解决 CORS 问题,我添加了以下代码行
res.setHeader(Access-Control-Allow-Origin, *);
但是现在服务本身不起作用。
代码有什么问题吗?
【问题讨论】: