我正在尝试简单的事情。对 node express 进行 ajax 调用并基于它做一些事情。我无法访问 req.body,我的意思是当从 node.js 端调试时它是空的
Node 端。 我正在使用:
app.use(express.bodyParser());
这是我在 express 中的测试方法:
app.get('/courses', function(request, response) {
console.log("I have been hit"); //I Am getting here
});
Angular 边:
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;
});
}
};
});
我正在尝试访问(从 Node 端)
req.body.name
但是 body 总是空的,好像我什么都没发送。
最佳答案
您的 ExpressJS 测试处理程序实际上并未响应任何数据,这就是您返回空主体的原因。查看expressjs site for documentation .
基本上你想要这样的东西
app.get('/courses', function(request, response) {
console.log("I have been hit"); //I Am getting here
response.send('hello world');
});
其次,您正尝试通过获取请求发送数据。如果您看一下 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 请求。这意味着您更新您的 express 处理程序以响应 POST 而不是 GET。
app.get('/courses', function(request, response) {
response.send(request.body);
});
这是一个简单的“回声”处理程序。它只会将客户端发送给它的任何内容发回给客户端。如果您向它发送“Hello”,它会回复“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);
});
}
};
});
关于ajax - 使 Ajax 调用 Angular 到 Node.js (express.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687667/