Mar*_*ria 18 jquery request node.js
我想做的事情:
只需使用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.');
}
});
Run Code Online (Sandbox Code Playgroud)
服务器代码:
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/');
Run Code Online (Sandbox Code Playgroud)
正如我所说,它永远不会进入请求的"数据"事件.
评论:
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.');
}
});
Run Code Online (Sandbox Code Playgroud)
服务器代码:
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/');
Run Code Online (Sandbox Code Playgroud)
由于我想允许跨域请求,我添加了CORS的实现.
谢谢!
Bri*_*lay 19
要在node.js服务器端触发'data'事件,您必须POST数据.也就是说,'data'事件仅响应POSTed数据.将'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>
Run Code Online (Sandbox Code Playgroud)
一些有用的行可以帮助您调试服务器端:
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');
Run Code Online (Sandbox Code Playgroud)
节点端的数据事件的目的是构建主体 - 它针对单个http请求多次触发,对于它接收的每个数据块一次.这是node.js的异步特性 - 服务器在接收数据块之间进行其他工作.