【发布时间】:2014-06-22 13:51:34
【问题描述】:
我有两个带有 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.in 我的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.
所以我在网上和 stackoverflow 上搜索了一些主题,然后我找到了 this 和 this 。根据这些主题,我将服务器中的响应标头更改为以下内容:
res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));
但是这不起作用。我尝试使用 firefox、chrome 并使用 Telerik Fiddler Web Debugger 检查请求,但服务器仍处于挂起状态,我收到 Access Control Allow Origin 错误。
【问题讨论】:
-
您可能需要一些额外的标头,请参阅此帖子:stackoverflow.com/questions/7067966/… IIRC 您至少需要允许的方法之一。
-
我也用this回答解决了我的问题。问题出在帖子上。
标签: javascript node.js angularjs angularjs-service