0

I've an http server in node [not express]. On button click I've a get method, which then pulls documents from mongodb (using mongoose) and displays it on angular page.

on button click:

       $http.get('/get').success(function(response){
         console.log(response);
       //logic to store JSON response of database and perform repeat to display each document returned on UI
       });

In Node code where server is created using http.createServer instead of express:

     if(req.url==="/get"){
      res.writeHead(200,{'content-type':'text/plain'});
      modelName.find({}, 'property1 prop2 prop3', function(err,docs){
        res.write('response...:  '+docs);
       });
     }

Here is my issue: I'm able to send response from node js to angular js but how to parse it? If I don't add 'response...:' before docs then I get an error msg 'first argument should be a string or buffer'. On angular I get response like:->

      response...:{_id:....1, prop1: 'a',prop2: 'b',prop3: 'c'},
      {_id:....2, prop1: 'ab',prop2: 'bc',prop3: 'cd'}

I want to display documents as a tabular format

3
  • 1
    Send json instead of plain string like: res.write({'response':docs}); Commented Dec 16, 2015 at 11:50
  • Still getting same error 'first argument should be a string or buffer' Commented Dec 16, 2015 at 12:02
  • You can actually set Content-Type:'application/json' . If you are getting the same error after this also do res.send(JSON.stringify(docs)); Commented Dec 16, 2015 at 12:06

1 Answer 1

0

I don't know your exact setup, but I think you should transfer application/json instead of text/plain.

You cannot simply concatenate a string to docs, you need to return either only just docs (to transfer as an array) or write res.write({'response':docs}) (to transfer as an object).

Consider moving from $http to a resource service. In your resource service, you need to set isArray to false if you want to transfer as an object or to true if you transfer as an array: https://docs.angularjs.org/api/ngResource/service/$resource

Sign up to request clarification or add additional context in comments.

3 Comments

still getting same error 'first argument should be a string or buffer'.
Do look into the request in Firefox/Chrome dev tool to see what type the response is, I suspect it is still plain text.
Are you getting this error from Node or in the browser. Either way, can you post the stack trace?

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.