[英]Making Ajax call Angular to Node.js (express.js)
我正在尝试简单的事情。 对node express进行ajax调用并根据它执行某些操作。 我无法访问req.body,我的意思是当从node.js端调试时它是空的
NODE SIDE。 我在用:
app.use(express.bodyParser());
这是快递中的矿山测试方法:
app.get('/courses', function(request, response) {
console.log("I have been hit"); //I Am getting here
});
角砾侧:
eventsApp.factory('MainConnector', function($http, $q, $resource ) {
return {
mainConnection: function( ) {
var requestBody = {
id: 3,
name: 'testname',
lastname: 'testlastname'
}
$http.get("http://localhost:3000/courses", requestBody)
.success(function(data, status, headers, config) {
console.log("this is coming from wherever:" + data);
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
};
});
我正在尝试访问(从节点端)
req.body.name
但身体总是空的,好像我没有发送任何东西。
你的ExpressJS测试处理程序实际上没有响应任何数据,这就是为什么你得到一个空体。 查看expressjs网站以获取文档 。
基本上你想要这样的东西
app.get('/courses', function(request, response) {
console.log("I have been hit"); //I Am getting here
response.send('hello world');
});
其次,您正尝试使用get请求发送数据。 如果您查看angularjs文档,您将看到$http.get
只接受1个参数,即url。
这意味着你想要的AngularJS工厂更像是这样的:
eventsApp.factory('MainConnector', function($http, $q, $resource ) {
return {
mainConnection: function( )
$http.get("http://localhost:3000/courses")
.success(function(data) {
console.log("this is coming from wherever:" + data);
});
}
};
});
但是,假设您确实想要向服务器发送内容,您想要的是POST请求。 这意味着您更新快递处理程序以响应POST而不是GET。
app.get('/courses', function(request, response) {
response.send(request.body);
});
这是一个简单的“echo”处理程序。 无论客户端发送给客户端,它都会发送回客户端。 如果你发送“Hello”,它将回复“你好”。
和相应的AngularJS服务工厂
eventsApp.factory('MainConnector', function($http, $q, $resource ) {
return {
mainConnection: function( )
var data = {name: "hello"};
$http.post("http://localhost:3000/courses", data)
.success(function(data) {
console.log("this is coming from wherever:" + data);
});
}
};
});
事实证明,这是两个问题。 是的,使用GET和发送有效负载存在此问题。 但是,这并没有解决问题。 问题出在CORS中。 这就是我修复它的方法:
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'content-type, Authorization, Content-Length, X-Requested-With, Origin, Accept');
if ('OPTIONS' === req.method) {
res.send(200);
} else {
next();
}
};
和
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(allowCrossDomain);
app.use(app.router);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.