无法在我的 REST API 中实现'PUT'方法 REST http 请求时出错



我正在尝试使用猫鼬方法创建一个REST API,因为当我试图在特定文章部分实现PUT模型时。当我从Postman

发送PUT请求时然后我在控制台中得到以下错误:

TypeError: Cannot read properties of undefined (reading 'title')
at E:REST apiWiki-APIapp.js:83:31
at Layer.handle [as handle_request] (E:REST apiWiki-APInode_modulesexpresslibrouterlayer.js:95:5)
at next (E:REST apiWiki-APInode_modulesexpresslibrouterroute.js:144:13)
at next (E:REST apiWiki-APInode_modulesexpresslibrouterroute.js:138:14)
at Route.dispatch (E:REST apiWiki-APInode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (E:REST apiWiki-APInode_modulesexpresslibrouterlayer.js:95:5)
at E:REST apiWiki-APInode_modulesexpresslibrouterindex.js:284:15    at param (E:REST apiWiki-APInode_modulesexpresslibrouterindex.js:365:14)
at param (E:REST apiWiki-APInode_modulesexpresslibrouterindex.js:376:14)
at Function.process_params (E:REST apiWiki-APInode_modulesexpresslibrouterindex.js:421:3)

错误截图

邮差界面截图

//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const app = express();
app.set('view engine', 'ejs');
app.use(express.static("public"));
mongoose.connect("mongodb://localhost:27017/wikiDB", { useNewUrlParser: true });
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
//*************** Request targeting all articles ***************
app.route("/articles")
.get(function (req, res) {
Article.find({}, function (err, foundArticles) {
if (!err) {
res.send(foundArticles);
} else {
res.send(err);
}
});
})
.post(function (req, res) {
const newArticle = new Article({
title: req.body.title,
content: req.body.content
});
newArticle.save(function (err) {
if (!err) {
res.send("Successfully added the article.");
} else {
res.send(err);
}
});
})
.delete(function (req, res) {
Article.deleteMany(
{}, function (err) {
if (!err) {
res.send("Successfully deleted all article.");
} else {
res.send(err);
}
}
)
});
//*************** Request targeting specific articles ***************
app.route("/articles/:articleTitle")
.get(function (req, res) {
Article.findOne({ title: req.params.articleTitle }, function (err, foundArticle) {
if (foundArticle) {
res.send(foundArticle);
} else {
res.send("No article matching that title was found.");
}
});
})
.put(function (req, res) {
Article.updateOne(
{ title: req.params.articleTitle },
{ title: req.body.title, content: req.body.content },
{ overwrite: true },
function (err, res) {
if (!err) {
res.send("successfully updated article!");
}
else {
res.send(err);
}
}
);
});

app.listen(3000, function () {
console.log("Server started on port 3000");
});

运行代码并从数据库连接它,并从邮递员发送http请求后,我只是看到这个错误,但无法看到我的数据库中的任何更改。

您需要使用body解析才能使用req.body,否则它将未定义。

添加以下行

app.use(express.json());
app.use(express.urlencoded());

const app = express();

最新更新