如何将信息从node.js返回到angular2

时间:2016-07-08 22:00:45

标签: javascript node.js angular

我将信息从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?**
};
是的,有人能帮帮我吗?谢谢。

1 个答案:

答案 0 :(得分:1)

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

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

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

// :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端点。搜索端点不符合该规范。