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

Posted

技术标签:

【中文标题】如何将 JQuery AJAX 请求中的数据发送到 Node.js 服务器【英文标题】:How to send data from JQuery AJAX request to Node.js server 【发布时间】:2012-11-08 19:56:14 【问题描述】:

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

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

客户端代码:

$.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.');
    
);

服务器代码:

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/');

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

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

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

提前谢谢大家。

编辑: 注释代码的最终版本,基于答案:

客户端代码:

$.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.');

);

服务器代码:

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/');

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

谢谢!

【问题讨论】:

是什么导致 ajax 调用触发? @Eric 我有一个按钮触发 ajax 调用。它工作正常,因为我在客户端上获得了响应数据。我的问题是在服务器上获取请求数据,我认为这是因为“数据”事件没有触发,我不知道为什么。 【参考方案1】:

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

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

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

客户:

<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>

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

服务器:

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

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

【讨论】:

感谢您回复@brion-finlay。实际上,我有一个触发 ajax 调用的按钮。我没有把它放在描述中,因为我有它的工作。问题是当请求到达服务器时,它不会触发“数据”事件。 我想我明白了——你的意思是服务器端的数据事件?问题是服务器端的数据事件发生在 POST 数据中,但在客户端中您指定了“jsonp”,这是一种用作 GET 回复的格式。我已经修改了答案以演示如何使用 POST 并触发数据事件。 就是这样!非常感谢,我错过了使用 JSONP 背后的概念,使用“util”也有很大帮助。除了您的示例之外,我还必须更改代码上的一些内容,我将对其进行描述更新。谢谢!

以上是关于如何将 JQuery AJAX 请求中的数据发送到 Node.js 服务器的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 jQuery $.ajax 将请求参数数组发送到 servlet?

如何通过 Ajax jQuery 将简单数据发送到 Django 中的views.py?

如何将 JQuery AJAX 请求中的字符串值传递给 Spring Boot 控制器?

如何使用发布请求将服务器端 jquery 数据表数据发送到服务器

Js原生Ajax和Jquery的Ajax

如何使用 jQuery 在不同的端口上发送 AJAX 请求?