我有一個表單和一個基本路由,一旦點擊提交按鈕,它就會將資料發送到資料庫。這是我正在使用的表單的代碼:
<form action="/posts" method="POST">
<label>
<p>Enter your post title: </p>
<input type = "text" id= 'title' name='title' value='enter name here'>
<p>Enter your post description:</p>
<input type = 'text' id = 'description' name ='description' value = 'your description here'>
<input type="submit" value = 'OK'>
</label>
</form>
然后這里是獲取資料并將其發送出去的代碼:
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save().then(data=> {
res.json(data);
})
.catch(err => {
res.json({message: err });
});
res.render('submission_complete.ejs');
});
在做了一些研究之后,我了解到 res.json() 結束了回應,res.render() 也是如此。問題是,我想發送資料,然后呈現一個新頁面,告訴用戶資料已成功呈現。我該如何實作這一目標?該代碼有效,但會引發錯誤,“UnhandledPromiseRejectionWarning: E??rror [ERR_HTTP_HEADERS_SENT]: 發送到客戶端后無法設定標頭”
uj5u.com熱心網友回復:
好的,如果你想渲染一個 ejs 模板并將資料發送到客戶端(使用該模板),express 允許我們簡單地通過呼叫回應render方法并不僅傳遞模板名稱,還傳遞一些資料來做到這一點在第二個論點中。在您的情況下,它將是:
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
});
post.save().then(data=> {
// Now i'm calling the render method and passing to it:
// - the name of the template i want to render(without extension if you called the app.set('view engine', 'ejs'))
// - an object containing the data property which is the response you get after the post has been saved
res.render('submission_complete', { data /* you can also write it as { post: data } */ });
})
.catch(err => {
res.json({message: err });
});
});
在模板中完成此操作后,您可以簡單地訪問這些變數,因此它會是(我猜您想做什么):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>POST SAVED SUCCESFULLY</h1> <!-- or whatever -->
<div>
<!-- it would be data.title if you passed '{ data }' as the second argument -->
<%= post.title %>
<br>
<!-- same as above, (data or post).description depending on what you passed as the second argument -->
<%= post.description %>
</div>
</body>
</html>
你也可以打電話
res.render('submission_complete', data);
并單獨訪問其屬性
<div>
<%= title %>
<br>
<%= description %>
</div>
就是說,我會添加您的代碼并進行一些改進以使其更清晰
// DISCLAIMER
// I'm calling the render method and not passing the file extension because
// i'm assuming you called 'app.set('view engine', 'ejs');' in the file where you
// declare the app variable
router.post('/', async (req, res) => {
// if you don't want to check the body of your request because you know you can receive only the right properties you can do all this stuff in just few lines
try {
const post = await new Post(req.body).save();
res.render('submission_complete', post);
} catch (e) { res.json({ message: err.message }); }
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343850.html
標籤:表达
