2017-05-14 118 views
1

我想从客户端发送数据到服务器(节点js)。我正在使用ajax。如何从节点js读取ajax请求的数据?

客户端:

$("#test_button").on("click",function(){ 
    //alert("shit"); 
    $.ajax(
     {url: "http://localhost:4000/ajax_check", 
     async: false, 
     type: "POST", 
     data: "{user:balayya,password:hero}", 
     success: function(result){ 
      alert("hooli"); 
     }}); 
}); 

服务器:

var app = require('express')(); 
var express = require('express'); 
var http = require('http').Server(app); 


http.listen(process.env.PORT || 4000, function() { 
    console.log('listening on *:4000'); 
}); 

app.use(express.static('publuc')); 

app.get('/', function(req, res) { 
    console.log("new entry page serving"); 
    res.sendFile(__dirname + '/main.html'); 
}); 

app.post('/ajax_check', function(req, res){ 
    console.log("someone came in here"); 
    console.log(req.query.data); 
}); 

所述的console.log()是印刷为 “未定义”。 什么是接收POST请求的正确方法,并从客户端的数据节点JS

+0

添加身体解析器这个工作。 – BloomBlack

+0

如果这是您的解决方案,您应该点击答案下的复选标记。它会帮助其他人在将来遇到这个问题。 – Adam

回答

0

尝试这样的:

$.ajax({ 
    url: "http://localhost:4000/ajax_check", 
    type: "POST", 
    data: { 
     user: "balayya", 
     password: "hero" 
    }, 
    success: function(result) { 
     alert("hooli"); 
    } 
}); 

和服务器使用req.body.param_name中读取相应的参数值:

app.post('/ajax_check', function(req, res){ 
    console.log("someone came in here"); 
    console.log(req.body.user); 
    console.log(req.body.password); 
}); 

另请注意,我从您的AJAX请求中删除了async: false,因为每次有人将此属性设置为false时,一只可怜的小猫死亡。

+0

为此工作添加一个body-parser。谢谢 。我保证,我不会杀死一只可怜的小猫。 – BloomBlack