gpt4 book ai didi

node.js - 从 express.js 发布请求将变量传递给 ejs 文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:39:45 25 4
gpt4 key购买 nike

提交表单后,我想呈现相同的页面,但在表单上方显示“消息发送成功”消息。使用此代码,我得到“引用错误,消息未定义”,当我使用相同的代码但在 GET 请求中它完美运行时,我觉得这很奇怪。 GET 和 POST 请求之间是否有不同的技术?

const express = require('express');
const app = express();
app.set('view engine', 'ejs');

app.get('/contact', (req, res) => {
res.render('contact');
});

app.post('/send', (req, res) => {
res.render('contact', {msg: 'Message sent successfully!'});
});
<section class="section-b">
<div>
<p><%= msg %></p>
<form action="send" id="contact-form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="emailContact" placeholder="E-mail"><br>
<textarea name="message" id="message" rows="10" placeholder="Your message here..."></textarea><br>
<button type="submit">Submit</button>
</form>
</div>
</section>

最佳答案

您需要检查变量 (msg) 是否已定义,在 .get("/contact") 请求中您没有发送 msg 作为参数,所以这就是你得到错误的原因

 <% if(typeof msg !== 'undefined') { %>
<p><%= msg %></p>
<% } %>

关于node.js - 从 express.js 发布请求将变量传递给 ejs 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54159361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com