如何将数据从 JQuery AJAX 请求发送到 Node.js 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13478464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:39:10  来源:igfitidea点击:

How to send data from JQuery AJAX request to Node.js server

node.jsjqueryrequest

提问by Marcelo Vitoria

What i want to do:
Simply send some data (json for example), to a node.js http server, using jquery ajax requests.

我想要做什么:
只需使用 jquery ajax 请求将一些数据(例如 json)发送到 node.js http 服务器。

For some reason, i can't manage to get the data on the server, cause it never fires the 'data' event of the request.

出于某种原因,我无法在服务器上获取数据,因为它永远不会触发请求的“数据”事件。

Client code:

客户端代码:

$.ajax({
    url: server,
    dataType: "jsonp",
    data: '{"data": "TEST"}',
    jsonpCallback: 'callback',
    success: function (data) {
        var ret = jQuery.parseJSON(data);
        $('#lblResponse').html(ret.msg);
    },
    error: function (xhr, status, error) {
        console.log('Error: ' + error.message);
        $('#lblResponse').html('Error connecting to the server.');
    }
});

Server code:

服务器代码:

var http = require('http');
http.createServer(function (req, res) {

    console.log('Request received');

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');

As i said, it never gets into the 'data' event of the request.

正如我所说,它永远不会进入请求的“数据”事件。

Comments:
1. It logs the 'Request received' message;
2. The response is fine, im able to handle it back on the client, with data;

评论:
1. 记录“收到请求”消息;
2.响应很好,我可以在客户端处理它,有数据;

Any help? Am i missing something?

有什么帮助吗?我错过了什么吗?

Thank you all in advance.

谢谢大家。

EDIT:
Commented final version of the code, based on the answer:

编辑:
根据答案评论了代码的最终版本:

Client code:

客户端代码:

$.ajax({
type: 'POST' // added,
url: server,
data: '{"data": "TEST"}',
//dataType: 'jsonp' - removed
//jsonpCallback: 'callback' - removed
success: function (data) {
    var ret = jQuery.parseJSON(data);
    $('#lblResponse').html(ret.msg);
},
error: function (xhr, status, error) {
    console.log('Error: ' + error.message);
    $('#lblResponse').html('Error connecting to the server.');
}
});


Server code:


服务器代码:

var http = require('http');
http.createServer(function (req, res) {

    console.log('Request received');

    res.writeHead(200, { 
        'Content-Type': 'text/plain',
        'Access-Control-Allow-Origin': '*' // implementation of CORS
    });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });

    res.end('{"msg": "OK"}'); // removed the 'callback' stuff

}).listen(8080, '192.168.0.143');
console.log('Server running at http://192.168.0.143:8080/');


Since i want to allow Cross-Domain requests, i added an implementation of CORS.


由于我想允许跨域请求,因此我添加了CORS的实现。

Thanks!

谢谢!

采纳答案by Brion Finlay

To get the 'data' event to fire on the node.js server side, you have to POST the data. That is, the 'data' event only responds to POSTed data. Specifying 'jsonp' as the data format forces a GET request, since jsonp is defined in the jquery documentation as:

要在 node.js 服务器端触发 'data' 事件,您必须发布数据。也就是说,'data' 事件只响应 POSTed 数据。指定 'jsonp' 作为数据格式会强制执行 GET 请求,因为 jsonp 在 jquery 文档中定义为:

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback

“jsonp”:使用 JSONP 加载到 JSON 块中。添加一个额外的“?callback=?” 到 URL 的末尾以指定回调

Here is how you modify the client to get your data event to fire.

以下是修改客户端以触发数据事件的方法。

Client:

客户:

<html>
<head>
    <script language="javascript" type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>

<body>
    response here: <p id="lblResponse">fill me in</p>

<script type="text/javascript">
$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.0.143:8080',
        // dataType: "jsonp",
        data: '{"data": "TEST"}',
        type: 'POST',
        jsonpCallback: 'callback', // this is not relevant to the POST anymore
        success: function (data) {
            var ret = jQuery.parseJSON(data);
            $('#lblResponse').html(ret.msg);
            console.log('Success: ')
        },
        error: function (xhr, status, error) {
            console.log('Error: ' + error.message);
            $('#lblResponse').html('Error connecting to the server.');
        },
    });
});
</script>

</body>
</html>

Some helpful lines to help you debug the server side:

一些有用的行来帮助您调试服务器端:

Server:

服务器:

var http = require('http');
var util = require('util')
http.createServer(function (req, res) {

    console.log('Request received: ');
    util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url

    res.writeHead(200, { 'Content-Type': 'text/plain' });
    req.on('data', function (chunk) {
        console.log('GOT DATA!');
    });
    res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8080);
console.log('Server running on port 8080');

The purpose of the data event on the node side is to build up the body - it fires multiple times per a single http request, once for each chunk of data that it receives. This is the asynchronous nature of node.js - the server does other work in between receiving chunks of data.

节点端的数据事件的目的是建立主体 - 每个 http 请求都会触发多次,每次接收到的数据块触发一次。这是 node.js 的异步特性——服务器在接收数据块之间做其他工作。