[英]Getting CORS error while connecting to a node js service from ionic framework
我有以下用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,*);
但是现在服务本身不起作用。
代码有什么问题吗?
您必须在*前后加上引号
res.setHeader(Access-Control-Allow-Origin, '*');
尝试使用此Google chrome扩展程序,它为我解决了很多问题。 https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.