【问题标题】:How to return information from node.js to angular2如何从node.js返回信息到angular2
【发布时间】:2016-07-09 09:54:57
【问题描述】:

我将信息从 angular 发送到 node.js 文件。我想知道如何将信息从 node.js 返回到 angular2。

index.js 中的代码

app.post('/', function(req,res){
var body = req.body;

 */ information received from angular2 file
        (...)
 */ then return information back to angular2 file. **How to do this?**
};

有人可以帮帮我吗?谢谢。

【问题讨论】:

    标签: javascript node.js angular


    【解决方案1】:

    首先你应该了解http请求的流程。

    这是一个使用 Angular 内置工具 $resource 的示例。

    以下是我从视图中的搜索文本框中将用户正在寻找的内容作为参数发送的搜索功能的表示:

    // :search is the param
    angular.module("MyApp")
      .factory("Search", function($resource) {
        return $resource("/api/search/:search", {}, {
          query : {
            method : "GET",
            isArray : true
          }
        });
    });
    

    这是控制器:

    所有这些控制器所做的就是观察是否有用户输入输入文本以进行搜索,并获取用户正在编写的内容并将其发送到后端,与上面的工厂/服务一起工作。此功能将数据发送到后端以获取查询,该查询是搜索结果的数组。

    angular.module('MyApp')
      .controller('AddCtrl', function($scope, $alert, Show, Search) {
        $scope.showName = '';
        $scope.data = {};
        $scope.addShowToModel = '';
    
        $scope.$watch('showName', function (tmpStr) {
          if (!tmpStr || tmpStr.length == 0) return 0;
            if (tmpStr === $scope.showName) {
              Search.query({ 'search': $scope.showName })
                .$promise.then(function(data) {
                  $scope.responseData = data;
                })
                .catch(function(response) {
                  console.log(response.error);
                });
            }
        });
    });
    

    这里是来自 Nodejs 的代码:

    app.get('/api/search/:search', function(req, res, next) {
      var searchParam = req.params.search
        .toLowerCase()
        .replace(/ /g, '_')
        .replace(/[^\w-]+/g, '');
    
      var parser = xml2js.Parser(); // npm module to convert xml to json
      request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + searchParam, function (error, response, body) {
    
          if (error) return next(error);
          parser.parseString(body, function (err, result) {
            if (result.Data.Series !== undefined) {
              // this is how you send the data to the frontend              
              return res.status(200).send(result.Data.Series);
            } else {
              res.status(411).send({message: searchParam + " wasn't found"});
            }
          });
    
      });
    });
    

    所以,简单地说:

    app.post('/', function(req, res){
      var body = req.body;
      console.log(body);
      return res.send(//whatever you need to send);    
    };
    

    有时您不想将数据发送到前端,而是发送状态码以查看操作的进行情况:

    app.post('/', function(req, res){
      if(everythingIsFine) {
        // send only status code
        res.sendStatus(200);
      }else {
        // in case you want to send status + message
        res.status(401).send('Invalid whatever thing');
      }
    };
    

    希望对你有帮助!

    编辑

    在服务中,您可以使用$http 代替$resource。这不是我回答的重要内容,只是告诉你。根据评论:

    使用 $http.get 代替 $resource 会更合适。 $resource 用于 RESTful CRUD 端点。搜索端点不符合该规范。

    【讨论】:

    • 彻底回答!但是,使用$http.get 而不是$resource 会更合适。 $resource 用于 RESTful CRUD 端点。搜索端点不符合该规范。它甚至可以简化Search 服务的使用。
    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多