【问题标题】:Send a response to Angular.js in Node.js在 Node.js 中向 Angular.js 发送响应
【发布时间】:2016-11-27 23:53:10
【问题描述】:

我将 Angular 与 Node 一起使用,并且会从 GET 请求向客户端控制器发送响应。

当我使用本机 Node 而不是 Express.js 时,我用来发送响应的代码行似乎不起作用

这是我的角度控制器:

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() 会抛出错误,除非我使用快速服务器

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.js 一起提供。使用本机 Node 服务器时如何将响应发送回 Angular?

【问题讨论】:

    标签: javascript angularjs json node.js


    【解决方案1】:

    res.json 不在HTTP response 的 API 中。

    标准方法是使用res.write() (docs) 然后res.end() (docs)。但在您的情况下,由于您没有发送大量数据,您可以使用快捷方式,只需使用 res.end()data 参数:)

    【讨论】:

    • 啊!很简单。我还必须对 json 数据进行字符串化: res.end(JSON.stringify(context));
    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2011-11-06
    • 2017-04-15
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多