【问题标题】:Req.body is empty objectReq.body 是空对象
【发布时间】:2020-09-13 06:53:24
【问题描述】:

不知道为什么?帮我调试!请

我尝试 console.log(req.body) 并得到 {}(空对象)

我尝试了很多方法,但我仍然不明白为什么。

我尝试使用中间件,但也没有用

const express = require("express");
const app = express();
const pug = require('pug');


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

app.set('view engine' , 'pug');
app.set('views', './views');
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)


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

app.post('/todos/create', (req,res)=> {
  console.log(req.body);
  db.get('todos').push(req.body).write();
  res.redirect('/todos');
});


app.listen(3000);```


this is file create.bug

```h1 Create New List
form(action="/todos/create", method="post", enctype="multipart/form-data")
        .form-group
            label(for="id") Id
            input#id(name="id" type="text")
        .form-group
            label(for="text") Text
            input#text(name="text" type="text")
        button Create```


----------




【问题讨论】:

  • 不要在您的帖子中添加垃圾文本来绕过要求您解释更多问题的要求 - 相反,请更详细地解释问题,例如作为您尝试过的哪种调试不起作用。查找如何创建 minimal reproducible example 也可能会有所帮助 - 考虑删除与问题不直接相关的代码。

标签: javascript node.js express


【解决方案1】:

body-parser 模块负责解析数据;你在你的代码中使用它,但我什至看不到你在哪里导入它。您至少需要在文件顶部导入它

var bodyParser = require('body-parser')

在此处查看其他使用示例:https://www.npmjs.com/package/body-parser

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多