Node / Express / Angular服务器端外部API请求

Node / Express / Angular Server side external API request

本文关键字:API 请求 外部 Angular Express Node 服务器端      更新时间:2023-09-26

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

步骤:

  1. 用户提交表单
  2. 客户端向服务器发出请求
  3. 服务器向外部API发出请求
  4. 服务器发送响应回客户端

我怎样才能做到这一点?

  $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);
    });
  });

你可以这样做:

// 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());