在Node.js中发送一个响应给Angular.js
我使用Angular和Node,并且会从GET请求发送一个响应给客户端控制器。
当我使用本地节点而不是Express.js时,用于发送响应的代码行似乎不起作用
这是我的angular度控制器:
app.controller('testCtrl', function($scope, $http) { $http.get('/test').then(function(response){ $scope = response.data; }); });
这本质上是路由到以下服务器脚本:
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);
除非使用express服务器,否则res.json()会引发错误
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);
我很确定json()函数附带节点。 如何在使用本机节点服务器时将响应发送回angular度?
res.json
不在HTTP响应的API中。
标准的方法是使用res.write()
( docs )然后res.end()
( docs )。 但在你的情况,因为你没有发送大量的数据,你可以使用快捷方式,只需使用res.end()
与data
参数:)