2016-05-05 58 views
2

在节点express中,当我尝试从表单中访问post值时,它显示request body undefined error。 这里是我的代码,request body undefined in node express

http.createServer(function(req, res) { 
    var hostname = req.headers.host.split(":")[0]; 
    var pathname = url.parse(req.url).pathname; 

    if (pathname==="/login" && req.method ==="POST") { 
    console.log("request Header==>" + req.body.username); 

}).listen(9000, function() { 
    console.log('http://localhost:9000'); 
}); 

请任何一个可以帮助我找到原因请求主体显示不确定的。

回答

1

如果你不使用express Web服务器,只是普通的HTTP启用body-parser中间件第一

var express = require('express') 
var bodyParser = require('body-parser') 

var app = express() 

// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false })) 

// parse application/json 
app.use(bodyParser.json()) 

app.use(function (req, res) { 
    res.setHeader('Content-Type', 'text/plain') 
    res.write('you posted:\n') 
    res.end(JSON.stringify(req.body, null, 2)) 
}) 
+0

我们使用相同的中间件,但服务器是http代理 – jicks