【问题标题】:How can I return the result of my Node controller to my application through AJAX?如何通过 AJAX 将 Node 控制器的结果返回到我的应用程序?
【发布时间】:2018-04-13 14:01:49
【问题描述】:

这是我的控制器代码

module.exports.key_i = function(req, res, next) {
  // console.log("We are here in webserver key_i");

  var k = req.body.KEY;
  // console.log(k);
  var requestOptions = {
    url: 'http://localhost:3000/api/key_i',
    method: 'POST',
    json:{
      key: k
    }
  }

  request(requestOptions, function(error, response, body) {
    if (error) {
      return res.status(500).send(error);
    } else {
      // console.log("Key_i "+body[0].price);
      var tt = { pp: body[0] };
    } 
  });
}

这里body[0] 包含所需的结果。如何将其传递给我的 AJAX 响应?

$.ajax({
  url: "http://localhost:3000/ajo",
  method: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({
    KEY: xy
  }),
  success: function(response) {
    console.log("Now response in topbt.js is");
    console.log(response);    
  }
});

我希望 body[0] 成为我的回应。我该怎么做?

【问题讨论】:

  • 键是数值吗?
  • API http://localhost:3000/api/key_i 是在同一台服务器上工作还是在不同的服务器上工作?

标签: jquery node.js ajax


【解决方案1】:

您应该使用res(也许是.json)返回到您的控制器(路由)。这样您的前端应用程序就可以从快速路由中获得响应。

文档:https://expressjs.com/en/4x/api.html

【讨论】:

    【解决方案2】:

    我假设您发出的请求将返回 JSON

    controller.js

    module.exports.key_i = function(req, res, next) {
      
      ...
    
      request(requestOptions, function(error, response, body) {
        if (error) {
          return res.status(500).send(error);
        }
        // assuming { pp: body[0] }; <- This is the object you want to send in response
        res.send({ pp: body[0] };)
         
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2020-05-07
      • 2017-04-02
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      相关资源
      最近更新 更多