2017-05-15 51 views
0

req.body簡直就是{}。任何表單數據都不在req.body中。請注意,它在郵遞員中效果很好。req.body是空的,就像{}

下面是服務器代碼:

const _ = require('lodash'); 
const express = require('express'); 
const hbs = require('hbs'); 
const bodyParser = require('body-parser'); 
const {ObjectID} = require('mongodb'); 
const {mongoose} = require('./db/mongoose'); 

var {authenticate, authenticateAdmin} = require('./middleware/authenticate'); 

const port = process.env.PORT; 
var app = express(); 

app.use(bodyParser.json()); 

app.set('view engine', 'hbs'); 

app.post('/users', (req, res) => { 
    var body = _.pick(req.body, ['email', 'password']); 
    console.log(body) 
}); 

app.listen(port,() => { 
    console.log(`Server is up on port ${port}`); 
}); 

下面是相關的HTML部分:

<form action="/users" method="post"> 
    <input type="email" name="email"> 
    <input type="password" name="password"> 
    <button type="submit">Done</button> 
</form> 

謝謝!

+1

使用'_.pick'之前,您是否打印過'req.body.email'? –

+0

req.body爲空,只需{} – brianalbin3

+1

您可以打印'console.log(req.body.email)'? –

回答

1
app.use(bodyParser.urlencoded({extended:true})) 

您需要添加這行編碼的身體。

2

這行添加到服務器和它的工作

app.use(bodyParser.urlencoded({ extended: true}));