Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 739
Melbourne2991 Avatar asked Feb 02 '14 12:02

Melbourne2991


1 Answers

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};
        }
      }
    });
like image 106
Nour Sammour Avatar answered Sep 18 '22 10:09

Nour Sammour