为了使’data’事件在node.js服务器端触发,您必须对数据进行POST。也就是说,“数据”事件仅响应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的异步特性-
服务器在接收数据块之间执行其他工作。



