Angular $ http.post和No'Access-Control-Allow-Origin'标题

我有两个应用程序与nodejs和angularjs.nodejs应用程序有这样的一些代码:

require('http').createServer(function(req, res) { req.setEncoding('utf8'); var body = ''; var result = ''; req.on('data', function(data) { // console.log("ONDATA"); //var _data = parseInput( data,req.url.toString()); var _data = parseInputForClient(data, req.url.toString()); switch (req.url.toString()) { case "/cubes": { 

和这个应用程序主机上的http://localhost:4000 .angularjs应用程序主机与节点http-server模块localhost://www.localhost:3030在我的一个angularjs服务我有这样的事情:

 fetch:function(){ var data = '{somedata:"somedata"}'; return $http.post('http://localhost:4000/cubes',data).success(function(cubes){ console.log(cubes); }); } 

但是当这个服务发送一个请求到服务器得到这个错误:

 XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access. 

所以我searchnetworking和stackoverflowfind一些话题,我觉得这个和这个 。 根据这些话题,我将服务器中的响应头改为如下所示:

 res.writeHead(200, { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*" }); res.end(JSON.stringify(result)); 

但这dose'nt work.I尝试与Firefox,铬,并检查与Telerik Fiddler Web Debugger的请求,但服务器仍悬而未决,我得到访问控制允许来源错误。

您执行POST请求,根据CORS规范生成预检请求: http : //hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/和https://developer.mozilla.org/en -US /文档/networking/ HTTP / Access_control_CORS

您的服务器还应该响应OPTIONS方法(除了POST),并且还返回Access-Control-Allow-Origin

你可以看到它的原因,因为当你的代码在Network选项卡(或Fiddler代理debugging器)中创build请求时,你应该看到ORIGIN头部的OPTIONS请求