如何使AngularJS的$ http请求到本地服务器上的应用程序?
目前的情况
我试图从Angular中发出$ http post请求,在我的控制器中定义了以下函数:
$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 post请求与下面定义的路由处理程序:
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中访问我的index.html, npm http-server
为http://127.0.0.1:8080
。 我有我的快速应用程序听下面的行app.listen(8080, '127.0.0.1');
相同的端口app.listen(8080, '127.0.0.1');
问题
当我尝试从http://127.0.0.1:8080
的前端发出http请求时,Angular函数会将我想要的JSON数据logging到控制台,但$ http请求不会生成,并且出现以下错误在Chrome控制台中:
POST http://127.0.0.1:8080/api/users 405 (Method Not Allowed)
我可以从Postman成功发送http post请求,并且可以很好地将json添加到我的mongodb集合中。
我得到这个错误,因为index.html /前端没有连接到Express应用程序? 基本上,我不明白这是如何工作的。 Express应用程序是否应该监听与index.html运行的端口相同的端口? 连接前端和后端的这种情况与在本地服务器上运行应用程序到互联网上运行应用程序时有什么不同?
如果有人能向我解释前端应该如何连接到后端,或者如果我做了其他任何错误,我将不胜感激。
谢谢!
您正试图发布不是JSON,但string:
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' } };