Node.js - 如何初始化/定义req.body?

时间:2013-12-07 14:32:41

标签: javascript node.js

我收到错误 - “无法读取未定义的属性'得分'在”var score - req.body.score“。为了做到这一点,我猜我需要定义和/或初始化'req.body'(我对Node.js很新),不知道我是怎么做到的?

这是我的Node.JS代码:

var http = require('http');
var express = require('express');

console.log('Game server running...'); 

http.createServer(function (req, res) { 
console.log('Player submitted high-score:');

var score = req.body.score;
  console.log(score);   

res.writeHead(200, {'Content-Type': 'text/plain'}); 
res.end('_testcb(\'"Your high-score has been submitted."\')'); 
}).listen(80);

下面是带有输入文本字段和提交按钮的HTML:

Your score: <input id="score" name="score" type="text"></input>
<button id="SubmitBtn" type="submit">Submit</button>

以下是HTML中的JavaScript(以防它有助于回答我的问题):

<script> 
 $(document).ready(function() {
$('#SubmitBtn').click(function (event) {
$.ajax({ 
url: 'http://localhost',
data: { score : $("input[name='score']").val() },
dataType: "jsonp", 
jsonpCallback: "_testcb", 
cache: false, 
timeout: 5000, 
success: function(data) { 
    $("#test").append(data); 
}, 
error: function(jqXHR, textStatus, errorThrown) { 
    alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown); 
} 
}); 
});
}); 

基本上,我想从HTML文档中获取一个名为“score”的输入文本字段的输入,但是在'var score - req.body.score'处获得错误“无法读取未定义的属性'得分'” 。猜测我需要在某处初始化/定义'req.body但我不知道怎么做?任何人都可以帮助我吗?

另外,我在网上发现有关初始化/定义'res.body'的信息,可能有用吗?

req.on('response', function (res) {
    res.body = "";
    res.on('data', function (chunk) {
        res.body += chunk;
    });

res.on('end', function () {
     console.log(res.body);
});
});

由于

2 个答案:

答案 0 :(得分:0)

request.body属性由bodyParser中间件填充,因此您必须将其包含在node.js应用程序中

app.use(express.bodyParser())

所以

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

console.log('Game server running...'); 

app.use(express.bodyParser())

console.log('Player submitted high-score:');

app.get('/', function(req, res) {
    var score = req.body.score;
    console.log(score);   
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('_testcb(\'"Your high-score has been submitted."\')'); 
});

app.listen(80);

req是包含当前请求数据的请求,res是您从服务器发回的响应,因此尝试从您发回的respone中获取输入数据不会起作用。

答案 1 :(得分:0)

我不知道某些“中间件”是否提供req.body,但是要继续沿着这条路走下去:

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

console.log('Game server running...'); 

http.createServer(function (req, res) { 
    console.log('Player submitted high-score:');

    var bodyParts = [];

    req.on("data", function(part) {
        bodyParts.push(part);
    });

    req.on("end", function() {
        var body = Buffer.concat(bodyParts).toString("utf8");
        var data = qs.parse(data);

        var score = data.score;
        console.log(score);

        res.writeHead(200, {'Content-Type': 'text/plain'}); 
        res.end('_testcb(\'"Your high-score has been submitted."\')'); 
    });
}).listen(80);