req.body未定义...我该如何解决

时间:2020-02-28 09:14:53

标签: node.js express body-parser

[  server.js  ]

const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;

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

const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);

const connection = mysql.createConnection({
    host: conf.host,
    user: conf.user,
    password: conf.password,
    port: conf.port,
    database: conf.database
});

connection.connect();

app.get("/api/users", (req, res) => {
    connection.query(
        "select * from users where isDeleted = 0",
        (err, rows, fields) => {
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        }
    );
});


app.post("/api/users", (req, res) => {
    let sql = "insert into users values (null,?,?,now(),now(),0)";
    let name = req.body.name;
    let dsc = req.body.dsc;
    let params = [name, dsc];
    console.log(params);
    connection.query(sql, params,
        (err, rows, fields) => {
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        });
});

app.delete("/api/users/:id", (req, res) => {
    let sql = "update users set isDeleted = 1 where id = ?";
    let params =[req.params.id];
    connection.query(sql,params,
        (err, rows, fields)=>{
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        });
});

app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));

描述错误

我正在尝试将表单数据发送到我的API,但是由于某些原因req.body未定义。

要复制

重现行为的步骤:

创建一个新请求 输入您的API端点URL 选择主体选项卡,然后选择表单数据选项卡 输入您要发送的表单数据的键名,以便您的API可以识别它,然后输入值。 单击发送,您应该获得状态码为200的响应。如果收到像我这样的错误,告诉我req.body未定义,那么您将遇到与我相同的问题。

2 个答案:

答案 0 :(得分:0)

  1. 您正在使用bodyparser.json()。从文档中,这将解析JSON中的请求。您最好使用bodyParser.urlencoded([options])

  2. 我建议改为使用express.urlencoded

阅读this进行澄清

答案 1 :(得分:0)

您缺少路由器

[  server.js  ]

const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express();
const port = process.env.PORT || 5000;

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

const data = fs.readFileSync("./database.json");
const conf = JSON.parse(data);

const connection = mysql.createConnection({
    host: conf.host,
    user: conf.user,
    password: conf.password,
    port: conf.port,
    database: conf.database
});

connection.connect();

// u need a router
const router = express.Router();

router.get("/api/users", (req, res) => {
    connection.query(
        "select * from users where isDeleted = 0",
        (err, rows, fields) => {
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        }
    );
});


router.post("/api/users", (req, res) => {
    let sql = "insert into users values (null,?,?,now(),now(),0)";
    let name = req.body.name;
    let dsc = req.body.dsc;
    let params = [name, dsc];
    console.log(params);
    connection.query(sql, params,
        (err, rows, fields) => {
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        });
});

router.delete("/api/users/:id", (req, res) => {
    let sql = "update users set isDeleted = 1 where id = ?";
    let params =[req.params.id];
    connection.query(sql,params,
        (err, rows, fields)=>{
            res.send(rows);
            // console.log(err);
            // console.log(rows);
        });
});

app.use(router);

app.listen(port, () => console.log(`Listening on port http://localhost:${port}`));