Express/Sequelize - PUT路由更新表单导致500个服务器错误
我正在处理一个放置路径以编辑书籍的详细信息。有三个必填字段 - 标题,作者,流派。如果我去编辑一本书的现有详细信息并删除其中一个字段,而不是获取sequelize验证错误,那么我会收到500个服务器错误。如果我只是尝试更改必需字段的文本,它会更新数据库。这里是我的个人书籍的获取和投放路线。Express/Sequelize - PUT路由更新表单导致500个服务器错误
// Get book detail + loans router.get("/details/:id", (req, res)=> {
const book = Book.findById(req.params.id);
const loans = Loan.findAll({where: {book_id: req.params.id}, include: [{ model: Patron}, {model: Book}]});
Promise.all([book, loans]).then(function(data) {
res.render('book_detail', {book: data[0], loans: data[1]});
});
});
/* POST update book. */
router.put("/details/:id", function(req, res, next){
Book.findById(req.params.id).then(function(book){
if(book) {
return book.update(req.body);
} else {
res.send(404);
}
}).then(function(book){
res.redirect("/books/");
}).catch(function(error){
if(error.name === "SequelizeValidationError") {
var book = Book.build(req.body);
book.id = req.params.id;
res.render("books/details/" + book.id, {book: book, errors: error.errors})
} else {
throw error;
}
}).catch(function(error){
res.send(500, error);
});
});
,这是我的PUG页面的样子--using方法重写包的格式字符串调用PUT:
extends layout block content
h1 Book: #{title}
include error
form(action='/books/details/' + book.id + "?_method=PUT", method="post")
P
label(for='title') Book Title:
input(id='title' name='title' width="175" type='text' value=book.title)
p
label(for='author') Author:
input(id='author' name='author' type='text' value=book.author)
p
label(for='genre') Genre:
input(id='genre' name='genre' type='text' value=book.genre)
p
label(for='genre') First Published:
input(id='first_published' name='first_published' type='text' value=book.first_published)
p
input(type='submit', value='Update')
任何想法?
回答:
router.post
和router.put
是不同的,请确保您发送正确的请求。由于您向页面发送了POST
请求,因此此请求将由router.post
处理,而不是router.put
,因此这500错误是从router.post
丢弃的。由于不允许在HTML表单中使用PUT
,因此您应该考虑以另一种方式更新您的图书。
以上是 Express/Sequelize - PUT路由更新表单导致500个服务器错误 的全部内容, 来源链接: utcz.com/qa/258336.html