【问题标题】:AngularJS $resource response being returned as array of characters from ExpressJSAngularJS $resource 响应作为 ExpressJS 的字符数组返回
【发布时间】:2014-02-25 22:32:04
【问题描述】:

我有一个 expressjs api,我的 angularJS $resource 对象可以与之对话。我已经使用 postman(用于测试 REST api 的 chrome 工具)发送了一个 post 请求,响应中的原始数据是:“已提交”。

标题:

Connection →keep-alive
Content-Length →9
Content-Type →text/html; charset=utf-8
Date →Sun, 02 Feb 2014 12:02:20 GMT
X-Powered-By →Express

当我在 Angular 中注销我的回复时,我得到以下信息:

Resource
    0: "S"
    1: "u"
    2: "b"
    3: "m"
    4: "i"
    5: "t"
    6: "t"
    7: "e"
    8: "d"
    $promise: undefined
    $resolved: true
    __proto__: Resource

我的快递代码:

exports.create = function(req, res) {
    new Product(req.body).save(function(err) {
        if (err) {
            res.send('There was an error: ' + err); 
        }
        else {
            res.send('Submitted')
        }
    });
};

AngularJs 工厂:

pantherServices.factory('Product', function($resource, Defaults) {
    var Product = $resource(Defaults.api_url + 'products', {productId: '@productId'} , {
            find: {
                method: 'GET',
                url: Defaults.api_url + 'products/:productId',
            },
            all: {
                method: 'GET',
                isArray: true
            }
        });

    return Product
});

我的控制器:

$scope.newProduct = {
    name: null,
    description: null,
    price: null,
    display_price: null,
    date_available: null
};

$scope.addNewProduct = function() {
    var newProduct = new Product($scope.newProduct);
    newProduct.$save(function(response, headers) {
        console.log(response)
    });
};

为什么要分解字符并将响应解析为数组,这是我的标头、angularjs 还是 express 的问题?

谢谢!

编辑:res.json 有同样的问题。

【问题讨论】:

    标签: javascript angularjs express


    【解决方案1】:

    我通过返回一个对象而不是一个字符串解决了这个问题。

    res.send({response: 'Created new Product Object'})

    【讨论】:

    • 我的 ASP.NET WebApi 应用程序中有相同的项目。通过返回 Dictionary 对象修复。
    【解决方案2】:

    在 Angular 资源中,可以选择包装响应 transformResponse,这应该可以解决问题

       $resource(appConfig.apiBaseUrl + '/newsletter/:id', {}, {
          update: {method: 'PUT'},
          weekly: {
            method: 'POST', params: {id: 'weekly'}, transformResponse: function (response) {
              // whatever you want to do
              return {html: response};
            }
          }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多