2017-12-02 195 views
0

我正在處理一個放置路徑以編輯書籍的詳細信息。有三個必填字段 - 標題,作者,流派。如果我去編輯一本書的現有詳細信息並刪除其中一個字段,而不是獲取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') 

任何想法?

+0

請添加實際的錯誤信息。即'的console.log(誤差);'。 – MikaS

+0

嘿那裏我得到的唯一的錯誤是500 - 內部嚴重錯誤 –

+0

你的意思是在瀏覽器中?我正在考慮你在終端上看到的錯誤消息,如果你添加了console.log,我上面提到了'res.send(500,error);'。 – MikaS

回答

0

router.postrouter.put是不同的,請確保您發送正確的請求。由於您向頁面發送了POST請求,因此此請求將由router.post處理,而不是router.put,因此這500錯誤是從router.post丟棄的。由於不允許在HTML表單中使用PUT,因此您應該考慮以另一種方式更新您的圖書。

+0

感謝您的回覆 - 我正在使用方法覆蓋包, https://github.com/expressjs/method-override –