試試下面的代碼:
客戶端的jQuery:
$.ajax({
type: 'POST',
url: 'http://localhost:3000/request',
data: {
test: "test"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success : function(result){
alert(result);
},
error : function(){
console.log("error")
}
});
在Node.js的
試試下面的服務器端代碼來處理/request
:
app.get('/request', function(req, res){
var data = {'TestKey':'TestValue'};
//For test at server side only
console.log('Sent this data to client:\n' + JSON.stringify(data));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
更新:代替
res.writeHead..
&
res.end..
您還可以使用:
res.json(data);
使從前端的AJAX請求到後端的路徑(例如/ getmyjson)...在express上,定義這個路由,然後發回你從你得到的json模塊。 –