[英]How to make $http requests from AngularJS to app on local server?
当前情况
我正在尝试在控制器中定义的以下函数中从Angular发出$ http发布请求:
$scope.sendUserData = function(){
var userData = JSON.stringify({
'firstName': $scope.firstName,
'lastName': $scope.lastName,
'email': $scope.email
});
console.log(userData); //this prints out the JSON I want
var config = {
headers: {
'Content-Type': 'json'
}
};
$http.post('/api/users', userData, config)
.success(function(data){
console.log(data);
})
.error(function(data){
console.log('Error: ' + data)
});
我有一个Express API,我想使用下面定义的路由处理程序接收此$ http发布请求:
router.route('/users')
.post(function(req, res){
var user = new User();
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
user.email = req.body.email;
user.save(function(error){ //add into mongodb
if(error){
res.send(error);
}
else{
res.json({message: 'User created'});
}
});
})
我正在使用npm http-server
运行前端,这使我可以在Chrome中访问位于http://127.0.0.1:8080
index.html。 我的Express应用程序使用以下行app.listen(8080, '127.0.0.1');
侦听同一端口app.listen(8080, '127.0.0.1');
问题
当我尝试从前端在http://127.0.0.1:8080
发出http请求时,Angular函数将我想要的JSON数据记录到控制台,但是未发出$ http请求,并且出现以下错误在Chrome控制台中:
POST http://127.0.0.1:8080/api/users 405 (Method Not Allowed)
我可以成功地从Postman发出http发布请求,并且看到JSON完美地添加到了mongodb集合中。
因为index.html /前端未连接到Express应用程序,我是否收到此错误? 从根本上讲,我不知道这是如何工作的。 Express应用程序应该监听index.html运行所在的端口吗? 将前端与后端连接的这种情况与本地服务器上运行的应用程序与Internet上运行的应用程序有何不同?
如果有人可以向我解释前端应如何连接到后端,或者如果我在做其他任何错误的事情,我将不胜感激。
谢谢!
您尝试发布的不是JSON而是字符串:
var userData = JSON.stringify({
'firstName': $scope.firstName,
'lastName': $scope.lastName,
'email': $scope.email
});
改为发布JSON
var userData = {
'firstName': $scope.firstName,
'lastName': $scope.lastName,
'email': $scope.email
};
供您参考,HTTP标头由$ http服务自动设置
var config = {
headers: {
'Content-Type': 'json'
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.