【问题标题】:angularjs using ng-resource to node.js back-end not sending correct POST requestangularjs 使用 ng-resource 到 node.js 后端未发送正确的 POST 请求
【发布时间】:2023-03-14 06:55:01
【问题描述】:

我想从我的 angularjs 应用程序向我的 node.js 服务器(使用 express)发出 POST 请求。我无法发送正确的 {key:value}。尽管研究了几个小时的解决方案,但我不知道如何正确编写参数以将它们返回到服务器端。我的结果是:'{"key":"value"}': ''。我哪里错了?

任何帮助表示赞赏,谢谢!

client.js

module.factory("Friends", function($resource) {
return $resource("https://myUrl/:id", {'id': '@id'} ,{
    mes: {method: 'POST', headers: {'content-Type': 'application/x-www-form-urlencoded'} , isArray : false }
});
});

module.controller('communityCtrl', ['$scope','$rootScope', 'Friends', function($scope,$rootScope, Friends) {
var value = "aValue";

$scope.getData = function()
{
    Friends.mes({id: 'jb'}, {key : 'value'} ).$promise.then(function(data){
    console.log(data);
    });
}
}]);

server.js

app.post('myUrl/jb', function(req, res) {
console.log("req.body : ", req.body);
res.json({code: 0, message: req.body.msg || ""}); 
});

输出

 req.body :  { '{"key":"value"}': '' }

【问题讨论】:

    标签: angularjs node.js express ngresource


    【解决方案1】:

    你试过 $http 吗?

    工厂定义:

    module
      .factory('friendsFactory', ['$http', function ($http) {
        return {
          post: function (id, data) {
            return $http.post('https://myUrl/' + id, data);
          },
          get: function () {
            return $http.get('https://myUrl/');
          }
        };
      }]);
    

    在您的控制器内:

    module
      .controller('friendsController', ['friendsFactory', function (friendsFactory) {
        friendsFactory.post(1, {id: 1})
          .then(function (res) {
            // success
            console.log(res.data);
          })
          .catch(function (err) {
            // there has been an error
            console.error(err.data);
          });
      }]);
    

    在您的 node.js API 端点中,req.body 将是一个字符串或一个对象。

    注意:如果是字符串,请确保您使用的是 express 上的 body-parser 中间件。

    在节点服务器上:

    var express = require('express')
      , bodyParser = require('body-parser')
      app = express();
    
    app.use(bodyParser.urlencoded({extended: true});
    

    body-parser 中间件(除其他外)获取 req.body 中的有效负载,并将其替换为该数据的有效 java 对象表示。

    【讨论】:

    • 嗨@gavin,谢谢你的回答,它有效,但我想使用 $resource 而不是 $http 来执行这些请求。有什么想法吗?
    • 我已经重新回答了这个问题 - 希望它可以解决您的错误并提供一个 $resource 工作的小例子。
    【解决方案2】:

    TL;DR 解决您的问题

    您的代码中的问题可能是以下行:

    Friends.mes({id: 'jb'}, {key : 'value'} ).$promise.then(function(data){
    

    尝试将其更改为:

    Friends.mes({id: 'jb', key: 'value'}).$promise.then(function(data){
    

    完成此操作后,服务器路由上的 req.body 对象将包含以下 {id: 'jb', key: 'value'} 而不是 { '{"key":"value"}': '' }

    $resource 应用示例:

    我创建了一个使用 $resource 获取和发布到 API 的小示例。

    ./public/index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>title</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-resource.min.js"></script>
        <script src="script.js"></script>
      </head>
      <body ng-app="app" ng-controller="friendController as vm">
        <div>
          {{vm.friend}}
        </div>
        <button ng-click="vm.getFriend()">Get User</button>
        <button ng-show="vm.friend" ng-click="vm.messageFriend(vm.friend)">Message Friend</button>
      </body>
    </html>
    

    ./public/script.js

    angular.module('app', ['ngResource'])
    
    .factory('friendFactory', ['$resource', function ($resource) {
      return $resource(
        '/api/v1/friends/:id',
        {id: '@_id'},
        {
          mes: {
            method: 'POST',
            headers: {'content-Type': 'application/x-www-form-urlencoded'},
            isArray : false,
            params: { message: true }
          }
        }
      );
    }])
    
    .controller('friendController', ['friendFactory', function (friendFactory) {
      var vm = this;
    
      vm.friend = null;
      vm.getFriend = _getFriend;
      vm.messageFriend = _messageFriend;
    
      function _getFriend() {
        friendFactory.get({id: 1})
          .$promise
          .then(function (res) {
            console.log(res);
            vm.friend = res;
          });
      }
    
      function _messageFriend(friend) {
    
        /* method 1: call $mes on a friend object: */
    
        // vm.friend.$mes({message: 'A message'})
        //   .then(function (friend) {
        //     vm.friend = friend;
        //   });
    
        /* method 2: call mes on the resource: */
    
        friendFactory.mes({_id: 1, message: 'A message'})
          .$promise
          .then(function (friend) {
            vm.friend = friend;
          });
      }
    
    }]);
    

    index.js - 托管页面并公开简单 api 的 node.js 服务器

    var express = require('express')
      , path = require('path')
      , app = express()
      , bodyParser = require('body-parser');
    
    app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
    app.use(express.static(path.join(__dirname, './public')));
    
    var friends = [
      { _id: 0, name: 'A' },
      { _id: 1, name: 'B' },
      { _id: 2, name: 'C' },
      { _id: 3, name: 'D' }
    ];
    
    app.get('/api/v1/friends', function (req, res) {
      return res.send(friends);
    });
    
    app.get('/api/v1/friends/:id', function (req, res) {
      for (var i = 0; i < friends.length; i++) {
        if (friends[i]._id == req.params.id) return res.send(friends[i]);
      }
      return res.status(404).send('Not found');
    });
    
    app.post('/api/v1/friends/:id', function (req, res) {
      for (var i = 0; i < friends.length; i++) {
        if (friends[i]._id == req.params.id) {
          friends[i].message = req.query.message;
          return res.send(friends[i]);
        }
      }
      return res.status(404).send('Not found');
    });
    
    app.listen(8080, function () {
      console.log('Server running');
    });
    

    这个例子有一个简单的 API,可以让你

    1. 获取好友列表
    2. 结交一个朋友
    3. 向朋友发布消息(我假设这就是您的 mes 的含义?)。发布时 - message 将作为查询字符串参数 (req.query.message) 或正文 (req.body.message) 使用。

    在本例中,它简单地将“消息”附加到朋友并返回对象。

    注意事项(在friendController): 默认情况下,在现有朋友对象上调用$mes会返回一个承诺,因此无需链接.$promise

    对资源本身调用mes不会返回承诺,因此需要$promise

    【讨论】:

    • 嗨@gavin,感谢您抽出宝贵时间,非常感谢。不幸的是,我仍然有我的 req.body 问题:{ '{"key":value}': '' } 你给我的修改。奇怪的东西:我用邮递员发送了一个请求,它工作正常,但我的代码没有。所以我认为这不是 node.js 问题。我应该给你看什么代码行?
    • 奇怪,你能不能在服务器上使用console.log(req.body) 和console.log(req.query) 看看你有什么?
    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2016-07-03
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多