【问题标题】:How to make $http requests from AngularJS to app on local server?如何从 AngularJS 向本地服务器上的应用程序发出 $http 请求?
【发布时间】:2016-10-08 09:29:56
【问题描述】:

现状

我正在尝试在我的控制器中定义的以下函数中从 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。我让我的快速应用程序使用以下行 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 post 请求,并且我看到 JSON 完美地添加到我的 mongodb 集合中。

我收到此错误是因为 index.html/front end 没有连接到 Express 应用程序吗?从根本上说,我不明白这是如何工作的。 Express 应用程序是否应该侦听运行 index.html 的同一端口?这种前端和后端连接的情况,与应用在本地服务器上运行时和应用在互联网上运行时有何不同?

如果有人可以向我解释前端应该如何连接到后端,或者如果我做错了什么,我将不胜感激。

谢谢!

【问题讨论】:

  • 看起来这个问答对你有帮助:stackoverflow.com/questions/24415376/…
  • 我认为,你不能在同一个端口 8080 上运行 2 个不同的应用程序。只需在其他端口上运行 Express 应用程序,例如 5000,然后从你的 Angular 向 127.0.0.1:5000 发出 http 请求应用
  • 谢谢@sergiy.dragunov 我试过这个但遇到了另一个问题。我为它创建了一个新帖子:stackoverflow.com/questions/37696978/…

标签: javascript angularjs node.js express mean-stack


【解决方案1】:

您尝试发布的不是 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'
    }
};

【讨论】:

猜你喜欢
  • 2020-12-26
  • 1970-01-01
  • 2015-02-24
  • 2023-01-31
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
相关资源
最近更新 更多