Javascript 向Node.js中的Angular.js发送响应
Im使用Angular with Node,希望从GET请求向客户端控制器发送响应 当我使用原生节点而不是Express.js时,我用来发送响应的代码行似乎不起作用 这是我的角度控制器:Javascript 向Node.js中的Angular.js发送响应,javascript,angularjs,json,node.js,Javascript,Angularjs,Json,Node.js,Im使用Angular with Node,希望从GET请求向客户端控制器发送响应 当我使用原生节点而不是Express.js时,我用来发送响应的代码行似乎不起作用 这是我的角度控制器: app.controller('testCtrl', function($scope, $http) { $http.get('/test').then(function(response){ $scope = response.data; });
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);
res.json()抛出错误,除非我使用express服务器
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()函数是随node一起提供的。使用本机节点服务器时,如何将响应发送回angular?
res.json
不在的API中
标准方法是使用
res.write()
(),然后使用res.end()
()。但在您的情况下,由于您没有发送大量数据,因此可以使用快捷方式,只需使用res.end()
和data
参数:)ah!这么简单。我还必须对json数据进行字符串化:res.end(json.stringify(context));