简体   繁体   English

如何将HTTP Post Request结果呈现给哈巴狗?

[英]How to Render HTTP Post Request result to pug?

When a user clicks on the form, I send a http post request to database server. 当用户单击表单时,我向数据库服务器发送一个http发布请求。 Which in turn sends post request back to user server. 依次将发布请求发送回用户服务器。

My problem is that I can't post this database result recieved from database server to pug. 我的问题是我无法将此数据库结果从数据库服务器发布到pug。 I am not sure how to implement AJAX here. 我不确定如何在这里实现AJAX。

I have tried sending the server http request itself, doesn't work. 我尝试发送服务器http请求本身,但是不起作用。 I have also tried to render the results to the pug file in the code as well, not luck! 我也尝试将结果也渲染到代码中的pug文件中,而不是运气!

script.js: 的script.js:

// analyze sentiment button
function analyzeSentiment() {
    // get and post filter to the backend for sentiment score    
    let form = $("#searchSentiment-form");
      let query = form.serialize();
    console.log(query);
    $.post('/', query);
}

pug file 哈巴狗文件

 form#searchSentiment-form(action='javascript:analyzeSentiment()', method='POST')
        input(type="text" id="sentimentFilter" name="sentimentFilter" placeholder="Search a filter" required)
         button(type="submit" id="sentiAnalysis" name="sentiAnalysis") ANALYZE

index.js index.js

 if(req.body.sentimentFilter) {
        // 1) Convert Tweet into JSON 
        tweetJSON = { sentimentFilter: req.body.sentimentFilter };
        console.log("Analyze this:", tweetJSON)

        // 2) Send via HTTP post request to the ANALYSIS-SERVER
        request({
            url: "http://LoadBalancer-1284897978.us-west-2.elb.amazonaws.com",
            method: "POST",
            json: true,   // <--Very important!!!
            body: tweetJSON
        }, function (error, response, body){
          if(error) {
            console.log("HTTP POST: Sending tweets to analysis-server Failed", error);
          } else {
            console.log("Success! Send sentiment request to analysis-server");
            }
          });

      //  receiving post result from server with results              
      } else if (req.body.score) {
         let score = req.body.score;

           res.render('index', {score:score});
          let JSONscore = { userScore: score};
               // 2) Send via HTTP post request to the LOAD-BALANCER FOR TWITTER-SERVER
        request({
          url: "http://52.26.216.28:3000",
          method: "GET",
          json: true,
          body: JSONscore
         }, function (error, response, body){
           if(error) {
            console.log("ERROR: COULD NOT SEND SCORE TO OWN USER-SERVER...", error);

           } else {
            console.log("SUCCESSFULY SENT SCORE TO OWN USER!..");
           }
        });

          console.log("Received Score is ", req.body.score);

       } 

Your question states that you send the request to the database server which then sends the request to the node.js server, this is not correct. 您的问题表明您将请求发送到数据库服务器,然后再将请求发送到node.js服务器,这是不正确的。 The user sends the request to the node.js server, which then creates a new request to the database server. 用户将请求发送到node.js服务器,然后该服务器将新请求创建到数据库服务器。 When the response is received by the node.js server in the callback, at that time you want to send the final response back to the client. 当回调中的node.js服务器接收到响应时,此时您希望将最终响应发送回客户端。

If you want to do this in the client without reloading the template then you need to: 如果要在客户端中执行此操作而不重新加载模板,则需要:

  1. Only send JSON in the response, 仅在响应中发送JSON,
  2. Handle the response with jquery, and then 使用jquery处理响应,然后
  3. Update the DOM using jquery 使用jQuery更新DOM

First, only send JSON. 首先,仅发送JSON。 None of the two callbacks are sending a response back to the client, that's a really big problem and it will look like your server is hanging. 这两个回调都没有将响应发送回客户端,这是一个很大的问题,看起来您的服务器已挂起。

This is how to return the response from the database to the client in your first callback. 这是在第一个回调中将响应从数据库返回到客户端的方法。 Expressjs has a shortcut method on the response ( res ) object that cleanly and quickly sends a JSON payload back properly: Expressjs在response( res )对象上提供了一种快捷方法,该方法可以干净快速地将JSON有效负载正确发送回:

function (error, response, body){
  if(error) {
    console.log("HTTP POST: Sending tweets to analysis-server Failed", error);
  } else {
    console.log("Success! Send sentiment request to analysis-server");
    res.json(response);
  }
}

Make sure you have that in all callbacks, then let's move on to the second issue in your code, handling the Ajax response. 确保所有回调中都包含该代码,然后继续处理代码中的第二个问题,处理Ajax响应。

Here is the relevant part of the sample code from the jquery $.post docs : 这是jquery $.post docs中示例代码的相关部分:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  });

You'll want to add the .done and .fail functions to your ajax code so you have something listening for that response from the server. 您需要将.done.fail函数添加到您的ajax代码中,以便您可以监听来自服务器的响应。

Finally, you'll probably want to show the user the result, so add a div to your pug: 最后,您可能希望向用户显示结果,因此将div添加到您的哈巴狗:

form#searchSentiment-form(action='javascript:analyzeSentiment()', method='POST')
  input(type="text" id="sentimentFilter" name="sentimentFilter" placeholder="Search a filter" required)
  button(type="submit" id="sentiAnalysis" name="sentiAnalysis") ANALYZE
div#response

Then in your .done call you can display the results: 然后,在您的.done呼叫中,您可以显示结果:

// analyze sentiment button
function analyzeSentiment() {
    // get and post filter to the backend for sentiment score    
    let form = $("#searchSentiment-form");
      let query = form.serialize();
    console.log(query);
    $.post('/', query).done(function(data){
      console.log(data);
      $('#results').html(data);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM