1

Im using Angular with Node and would to send a response to the client-side controller from a GET request.

The line of code Im using to send the response seems not to be working when I use native Node as opposed to Express.js

Here is my angular controller:

app.controller('testCtrl', function($scope, $http) {

        $http.get('/test').then(function(response){ 

            $scope = response.data;

        });

});

This is routed to essentially the following server script:

http.createServer(function onRequest(req, res){ 

    if(req.method==='GET'){

        var scope = 'this is the test scope';

        res.json(scope); // TypeError: res.json is not a function           
    }   

}).listen(port);

res.json() throws an error unless I use an express server

var app = express();

app.all('/*', function(req, res) {

    if(req.method==='GET'){

        var scope = 'this is the test scope';

        res.json(scope); // OK!         
    }

 }).listen(port);

I was pretty sure the json() function came with node. How do I send a response back to angular when using a native Node server?

1 Answer 1

3

res.json is not in the API for HTTP response.

The standard way would be to use res.write() (docs) and then res.end() (docs). But in your case, since you're not sending a lot of data you can use a shortcut and just use res.end() with a data parameter :)

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

1 Comment

ah! so simple. I also had to stringify the json data: res.end(JSON.stringify(context));

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.