req.body returns post 为空

req.body returns empty on post

我对 Express 还很陌生。不知道我做错了什么...... 这是我的情况的快速模型。

app.js

const app = express();
const bodyParser = require('body-parser')
const port = 3000;

app.set('view engine', 'pug');
app.use('/static', express.static('./public'));

const urlEncoded = bodyParser.urlencoded({ extended: false });
const jsonParser = bodyParser.json();

app.get('/', (req, res) => {
  res.render('index')
});

app.get('/form', (req, res) => {
  res.render('form');
});

app.post('/', urlEncoded, (req, res) => {
  console.log(req.body);
});

app.listen(port, () => {
  console.log(`This app is listening on localhost:${port}`);
});

form.pug

block content
  form(action="/" method="post")
    label(for="name")
    input(for="name" id="name")

    input(type="submit")

控制台中的结果是一个空对象。

您混淆了 id 和 name tag.The name 属性用于引用 JavaScript 中的元素,或者在提交表单后引用表单数据,而这正是您缺少的您的 html 表格。因此,只需添加一个名称属性即可。

block content
  form(action="/" method="post")
    label(for="name")
    input(for="name" id="name" name = "name")

    input(type="submit")