简体   繁体   English

客户端JS向nodejs express服务器发送数据并响应

[英]Client JS sending data to nodejs express server and response

I am trying to make an upvote and downvote system in nodejs.我正在尝试在 nodejs 中制作一个upvote 和downvote 系统。 The client side javascript should handle the upvote and downvote functionality and send the data to the server, which will store the decisions of the user.客户端 javascript 应该处理 upvote 和 downvote 功能并将数据发送到服务器,服务器将存储用户的决定。

My question is how do I send the data to the server and how can I send back if the upvote or downvote was successfully saved?我的问题是如何将数据发送到服务器,如果成功保存了赞成票或反对票,我该如何发回?

Client side:客户端:

window.onload = function() {
  document
    .getElementsByClassName("upvote")[0]
    .addEventListener("click", function(event) {
      // tell the server that the user upvoted
    });  
};

And on the server I would do something like this I guess在服务器上,我想我会做这样的事情

app.get("/", function(req, res) {
  // save req data to a file
  if (savedToFile) {
    res.send("saved successfully");
  }
  else {
    res.send("error");
  }
});

I hope you are using pure javascript, then you can use Ajax to send get a request to the server like bellow inside the click event.我希望您使用的是纯 javascript,然后您可以使用 Ajax 向服务器发送 get 请求,如下所示在 click 事件中。

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var response = this.responseText; // here you get the response
    } 
    // handle 500 error state here
  };
  xhttp.open("GET", "server_url/upvote", true);
  xhttp.send();

After you save the data to database send the response as bellow将数据保存到数据库后,发送响应如下

app.get("/upvote", function(req, res) {
  // save req data to a file
  if (savedToFile) {
    res.status(200).send("saved successfully");
  }
  else { // if got any error
    res.status(500).send("error");
  }
});

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

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