20

我想要做什么:
只需使用 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的实现。

谢谢!

4

1 回答 1

20

要在 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 的异步特性——服务器在接收数据块之间做其他工作。

于 2012-11-20T18:00:14.693 回答