【问题标题】:Client JS sending data to nodejs express server and response客户端JS向nodejs express服务器发送数据并响应
【发布时间】:2020-04-16 15:51:30
【问题描述】:

我正在尝试在 nodejs 中创建一个赞成和反对的系统。客户端javascript应该处理upvote和downvote功能并将数据发送到服务器,服务器将存储用户的决定。

我的问题是如何将数据发送到服务器,如果成功保存了赞成票或反对票,我该如何发回?

客户端:

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

我猜我会在服务器上做这样的事情

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

【问题讨论】:

    标签: javascript node.js express http server


    【解决方案1】:

    我希望你使用的是纯 javascript,那么你可以使用 Ajax 在 click 事件中向服务器发送 get 请求。

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

    将数据保存到数据库后,发送如下响应

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

    【讨论】:

    • 我猜你的意思是这样写:app.get("/upvote", function(req, res) { ... });对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2014-09-07
    • 2016-07-21
    • 2020-08-17
    相关资源
    最近更新 更多