AngularJS $resource response being returned as array of characters from ExpressJS

眉间皱痕 提交于 2020-01-03 10:43:29

问题


I have an expressjs api that my angularJS $resource objects talk to. I have sent a post request with postman (a chrome tool for testing REST apis) and the raw data in the response is: "submitted".

The headers:

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

When I log out my response in angular I get the following:

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

My express code:

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 factory:

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
});

My controller:

$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)
    });
};

Why is it breaking up the characters and parsing the response as an array, is it an issue with my headers, angularjs or express?

Thanks!

EDIT: res.json had the same problem.


回答1:


in angular resource there is option to wrap the response transformResponse, that should solve the issue

   $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};
        }
      }
    });



回答2:


I solved the issue by returning an object instead of a string.

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



来源:https://stackoverflow.com/questions/21510415/angularjs-resource-response-being-returned-as-array-of-characters-from-expressj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!