NodeJS,我可以在客户端看到Request Payload中的数据,但我看不到服务器端请求对象中的数据

时间:2015-12-25 04:23:27

标签: javascript node.js

我正在尝试将数据从客户端发送到服务器nodeJS。但是在服务器上看不到数据。我错过了什么?
的index.html

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var testField = $('#testField').text();
$(document).ready(function() {
    $('#submit').on("click",function() {
        if ((!$('#testField').val())) {
            $('#error').text("Please enter Test");
        } else {
            $('#error').hide();
            console.log ("Ajax call");          
            console.log ("Inner Ajax call");
                $.ajax({
                    type: 'POST',
                    url: '/testUrl',
                    data: testField,
                    success: function(result) {
                        console.log ('Response Success:', result);
                    },
                    failure: function(result) {
                        console.log ('Response Failue:', result);
                    }
                });
        }
    });
});
</script>
</head>
<div id="testId">Test:<input type="text" name="testField" id="testField">     </div>
<div id="error"></div>
<div id="code"></div>
<div id="button"><input type="button" id="submit" value="Submit"></div>    
</html>

当我在testField中输入值并按回车键时,应该在server.js上收到它 以下是server.js的代码

var http = require('http');
var fs = require('fs');
var qs = require('querystring');

function send404Response (response) {
    console.log ("send404Response");
    response.writeHead(404, {"Context-Type" : "text\plain"});
    response.write("Error 404: Page not found");
    response.end();
}

function onRequest(request, response) {
    console.log ("onRequest");
    if (request.method == 'GET' && request.url == '/') {
        console.log ("onRequest - GET - Home page");
        response.writeHead(200, {"Context-Type" : "text\plain"});
        fs.createReadStream ('./index.html').pipe(response);
    } else if ((request.type == 'POST' || request.method == 'POST') && (request.url == '/testUrl')) {
        console.log ("onRequest - POST - testUrl - " + request.data);   //request.data is undefined - how to receive data.
        response.end();
    } else {
        send404Response(response);
    }
}

http.createServer(onRequest).listen(8888);
console.log("Server is now running");

request.data未定义,如上面代码的注释部分所述。我尝试通过node-inspector可视化请求对象。但我没有看到通过客户端发送到服务器的数据。请评论我错过了什么。
在此先感谢

1 个答案:

答案 0 :(得分:0)

看起来像重复的问题,请参阅下面的答案

function (req, res) { if (req.method == 'POST') { var jsonString = ''; req.on('data', function (data) { jsonString += data; }); req.on('end', function () { console.log(JSON.parse(jsonString)); }); } }

stackoverflow.com/questions/4295782/how-do-you-extract-post-data-in-node-js