【问题标题】:eventListener on button to exchange data between HTML client and node.js server按钮上的 eventListener 在 HTML 客户端和 node.js 服务器之间交换数据
【发布时间】:2017-09-08 13:44:09
【问题描述】:

我正在尝试在服务器和客户端之间传递一个 json 对象。到目前为止的服务器端看起来像:

var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
var bodyParser = require("body-parser");


var app = express();
app.use(express.static("public"));

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.post("/", function (req, res) {

    console.log('Request received');
    var return_value;

    req.on('data', function (chunk) {
        console.log('GOT DATA!');
        json = JSON.parse(chunk);
        json.access_date  =  "12.04.17";
        return_value = JSON.stringify(chunk);
    });

    res.writeHead(200, { 
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*' 
    });
    res.json(return_value);

})


var server = app.listen("8080")
console.log('Server running port 8080/');

将以下功能附加到按钮。

<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);

function passArg() {
    console.log("I'm here")
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.open("POST", "/", true);
    xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
                //var json = JSON.parse(xmlhttp.responseText);
                console.log("Data passed back: " + xmlhttp.responseText)
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    }

    var data = JSON.stringify({"email":"hey@mail.com","password":"101010"});
    xmlhttp.send(data);
}
</script>

现在单击控制台日志“我在这里”触发正常,但该函数在代码的 POST 部分返回 404 错误。我也不完全了解如何将数据从服务器传回客户端。方法res.end() 是正确的方法吗?

编辑:我已经编辑了脚本以反映答案。

【问题讨论】:

    标签: javascript html node.js xmlhttprequest


    【解决方案1】:

    我认为需要进行 2 项更改

    1

    正如@charietfl 所提到的,您可以通过包含express 端点的路径来简化您的xmlhttp.open() 调用。

    您目前没有调用您的 /callback 端点,所以我会将其放入您的 xhtmlhttp.open() 调用中。

    类似xmlhttp.open('POST', '/callback')

    2

    正如@Bshaps 所提到的,您还有一个期待GET 请求的端点,但您使用的是POST,所以正在更改

    app.get("/callback"...
    

    app.post("/callback"...
    

    【讨论】:

    • 谢谢,效果很好。但是,我仍然坚持如何将对象发送回客户端。如果您能对此有所了解,我将不胜感激。
    【解决方案2】:

    检查浏览器开发工具网络中的实际请求。可能会看到请求是 'http://localhost:8080/localhost:8080 ... 将协议添加到使用的 url

    xmlhttp.open("POST", "http://localhost:8080")
    

    或者直接设置为:

    xmlhttp.open("POST", "/")
    

    并添加一个post 路由服务器端

    【讨论】:

      【解决方案3】:

      问题是您的服务器正在接收一个 post 请求,但您的路由是一个 get 请求。

      变化:

      app.get("/callback", function(req, res){
      

      收件人:

      app.post("/callback", function(req, res){
      

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 2016-04-05
        • 2018-09-14
        • 1970-01-01
        • 2013-02-09
        • 2017-09-07
        • 2012-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多