Reputation: 1966
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?
Upvotes: 1
Views: 1911
Reputation: 17486
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 :)
Upvotes: 3