2016-05-05 57 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