NodeJS+Postman POST请求报错Cannot POST /bookstore求助
问题:Postman发送POST请求到
/bookstore报错Cannot POST /bookstore,GET请求正常 我在使用Postman发送POST请求到/bookstore时收到错误,错误页面显示如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot POST /bookstore</pre> </body> </html>
但GET请求访问/bookstore和/bookstore/:id都能正常工作。我原本编写的POST请求代码如下:
app.post("/bookstore", (req, res) => { const books = req.body; db.collection("bookstore") .insertOne(books) .then((result) => res.json(result)) .catch((err) => res.send(err)); });
完整项目代码如下:
db.js
const { MongoClient } = require("mongodb"); let dbConnection; module.exports = { connectToDb: (cb) => { MongoClient.connect("mongodb://localhost:27017/bookstore") .then((res) => { dbConnection = res.db(); return cb(); }) .catch((error) => { console.log(error); return cb(error); }); }, getDb: () => dbConnection, };
index.js
const express = require("express"); const { connectToDb, getDb } = require("./db"); const { ObjectId } = require("mongodb"); const e = require("express"); // init app and middleware const app = express(); app.use(express.json()); //db connection let db; connectToDb((xato) => { if (!xato) { app.listen(3000, () => { console.log("The 3000 port is installed"); }); db = getDb(); return db; } }); //routes app.get("/bookstore", (req, res) => { let mybook = []; // the collection name from mongoDB db.collection("bookstore") .find() .sort({ author: 1 }) .forEach((book) => mybook.push(book)) .then(() => { return res.json(mybook); }) .catch(() => { return res.send("there were an error"); }); // res.json({ MyWords: "I am coming from json res" }); }); app.get("/bookstore/:id", (req, res) => { if (ObjectId.isValid(req.params.id)) { db.collection("bookstore") .findOne({ _id: new ObjectId(req.params.id) }) .then((doc) => res.json(doc)) .catch((err) => res.send(err)); } else { res.send(" wrong id request"); } }); app.post("/", (req, res) => { const books = req.body; db.collection("bookstore") .insertOne(books) .then((result) => res.json(result)) .catch((err) => res.send(err)); });
我已经重启过Express服务器,但问题依旧,请求找出错误并修复!
解决方案
问题根源
你在index.js中实际注册的POST路由是根路径/,而非你预期的/bookstore。当你向/bookstore发送POST请求时,Express找不到对应的处理路由,因此返回Cannot POST /bookstore错误。
修复步骤
将index.js中的POST路由路径从/修改为/bookstore,与你最初编写的代码一致:
// 替换原有的app.post("/", ...)代码 app.post("/bookstore", (req, res) => { const books = req.body; db.collection("bookstore") .insertOne(books) .then((result) => res.json(result)) .catch((err) => res.send(err)); });
额外验证项
- 重启Express服务器,确保代码修改生效
- 在Postman中确认请求地址为
http://localhost:3000/bookstore,请求方法为POST - 在Postman的Body选项卡中选择
raw->JSON格式,传入合法的书籍数据示例:{ "title": "Node.js实战", "author": "张三", "price": 59.9 } - 确认MongoDB服务处于运行状态,且
bookstore数据库已存在
内容的提问来源于stack exchange,提问作者Sardor Sirojov
相关产品推荐
相关产品推荐

