xuniX
xuniX

Reputation: 75

AngularJS: AJAX return is a String and not an Object

I have a node.js server. This server has a small API. I build an App with AngularJS and my problem is that if I make an ajax-call to the server i get a string back and not an object.

Server API:

exports.api = function(req, res, next) {

  var path = req.body.path
  var method = req.body.method

  digest.request({
    host: 'xxx',
    path: path,
    port: 80,
    method: method,
    headers: { "User-Agent": "Bridge" }
  }, function (resX) {
    resX.on('data', function (data) {
      res.status(200).end(data)
    })
    resX.on('error', function (err) {
      res.status(200).end(err)
    })
  })
}

Call:

.controller('TestCtrl', function($scope, $http) {
  $http({
    url: 'http://localhost:8000/api',
    method: 'POST',
    data: {'method': 'GET', 'path': '/api'}
  }).success(function(data, status, headers, config) {
      console.log(data);
  }).error(function(data, status, headers, config) {
      console.log(data);
  })
})

I hope someone can help me because I despair.

Upvotes: 1

Views: 779

Answers (1)

st2rseeker
st2rseeker

Reputation: 483

I would suggest adding content type to the request according to your data (to let the function know what to expect back).

Additionally you could try using JSON utilities to convert the data to an object. E.g.:

http://www.quora.com/How-can-I-convert-JSON-format-string-into-a-real-object-in-JS

Depends on what you are actually getting back.

Upvotes: 1

Related Questions