且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据从客户端的 html 发送到 node.js 服务器?

更新时间:2023-11-09 12:17:28

你的ajax请求应该是这样的

Your ajax request should be like this

$.ajax({
    url: 'http://127.0.0.1:8090/',
    data: { "name": "John", "age":30, "car":null },
    type: 'POST'
    .....
})

并在 server.js 的 createServer 方法中更新这个

And in createServer method of server.js update this

if (req.method == 'POST') {
    console.log("POST");
    var body = '';
    req.on('data', function (data) {
        body += data;
        console.log("Partial body: " + body);
    });
    req.on('end', function () {
        console.log("Body: " + body);
    });
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('callback(\'{\"msg\": \"OK\"}\')');
}
else
{
    console.log("GET");
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('callback(\'{\"msg\": \"OK\"}\')');
}