6

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.

2 Answers 2

5

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};
        }
      }
    });
Sign up to request clarification or add additional context in comments.

Comments

3

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

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

1 Comment

I've had the same project in me ASP.NET WebApi app. Fixed by returning Dictionary object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.