私がやりたいこと:
jquery ajaxリクエストを使用して、node.js httpサーバーにデータ(jsonなど)を送信するだけです。
何らかの理由で、サーバーでデータを取得できません。リクエストの「データ」イベントが発生しないためです。
クライアントコード:
$.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. 'Request received' メッセージをログに記録します。
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/');
Cross-Domain リクエストを許可したいので、CORSの実装を追加しました。
ありがとう!