即使我使用app.use(Express.json()),ExpressJS-post方法-req.body也没有定义



我的代码是这样的-

const express = require("express");
const path = require("path");
const { open } = require("sqlite");
const sqlite3 = require("sqlite3");
const dbPath = path.join(__dirname, "moviesData.db");
const app = express();
app.use(express.json());
app.use(express.urlencoded({
extended: true
}))
let database = null;
const initializeDBAndServer = async () => {
try {
database = await open({
filename: dbPath,
driver: sqlite3.Database,
})
app.listen(5353, () => {
console.log(`server is running at http://localhost:5353/`)
})
} catch (error) {
console.log(`error: ${error.message}`);
process.exit(1)
}
}
initializeDBAndServer();
app.post("/myId", async (req, res) => {
const { id } = req.body;
console.log(`requested Id is ${id}`);
res.send(`requested Id id ${id}`);
})

我的请求是-

POST http://localhost:5353/myId/
Content-Type: "application/json"
{
"id": 123456 
}

控制台和响应来自相同的

requested Id is undefined

我使用过-app.use(express.json(((。它不起作用。并且还安装了body解析器,也进行了尝试。它也不起作用。

所以,请给我正确的代码来帮助我。

请求中的Content-Type不正确,应该是application/json,而不是"application/json":

Content-Type: application/json

最新更新