【问题标题】:Node / Express / Angular Server side external API requestNode / Express / Angular 服务器端外部 API 请求
【发布时间】:2015-12-16 05:30:36
【问题描述】:

我正在使用 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);
    });
  });

【问题讨论】:

    标签: javascript angularjs node.js api


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

    • npm install body-parser 并在服务器 js 文件中需要它,因为它现在单独提供:P
    • 这不起作用。使用帖子给了我这个错误:加载资源失败:net::ERR_CONNECTION_REFUSED
    • 客户端的帖子好像没有发给我 404(未找到)
    猜你喜欢
    • 2016-08-09
    • 2020-12-30
    • 2016-09-13
    • 1970-01-01
    • 2018-03-16
    • 2016-06-18
    • 2017-11-13
    • 2023-02-16
    • 2012-09-24
    相关资源
    最近更新 更多