Node / Express / Angular Server端外部API请求

时间:2015-09-18 23:46:40

标签: javascript angularjs node.js api

我使用Angular将表单输入保存到$ scope.tag。我无法使用表单信息作为参数进行客户端外部API调用,因此我需要将其传递给服务器。我怎样才能做到这一点?

步骤:

  1. 用户提交表单
  2. 客户端向服务器发出请求
  3. 服务器向外部API发出请求
  4. 服务器将响应发送回客户端
  5. 我怎样才能做到这一点?

      $scope.tag = '';
    
      // client side
      $http.get('/api')
        .then(function(response) {
          console.log(response);
      });
    
      // server side
      app.get('/api', function (req, res) {
      request('http://externalAPI.com/' + $scope.tag, function (req, res) {
        res.json(data);
        });
      });
    

1 个答案:

答案 0 :(得分:3)

您可以这样做:

// client side
  $http.post('/api', { tag: $scope.tag })
    .then(function(response) {
      console.log(response);
  });

  // server side
  app.post('/api', function (req, res) {
    console.log(req.query.tag);
    res.json({ status: 'success' });
  });

请记住在路由中间件之前加入app.use(bodyParser.json());

相关问题