简体   繁体   English

使用 express 时如何访问表单中的 ejs 数据

[英]How do i access ejs data in a form while using express

In the following code, I display the following HTML file upon user requests.在以下代码中,我根据用户请求显示以下 HTML 文件。 I also want to access the clubname and type datavalues inside my app.post() function in my app.js file.我还想在我的 app.js 文件中访问我的 app.post() 函数中的俱乐部名称和类型数据值。

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<% include templates/adminheader.ejs %>
<h1>Respond to Club Requests</h1>

<form name="clubform" method="post">
    <% for (var i in clubreq){%>
        Club Name:<%= clubreq[i].clubname %><br><br>//I want to access this variable in my app.post() function
        Club Type:<%= clubreq[i].type %><br><br>
        <input type="submit" value="accept"/><br><br><hr>
    <%} %>
</form>

</body>
</html>

Inside app.js .app.js里面。 Here I am rendering the HTML file upon user request在这里,我根据用户请求呈现 HTML 文件

app.get('/clubreq', function(req, res, next){
        res.render('clubreq', {
            title: 'Club Requests',
            "clubreq" : docs
        });       
});
app.post('/clubreq', function(req, res, next){
    //I want to access clubname and type datavariables here and store it in my mongodb database
});

Let's start with getting the info into the form.让我们从获取信息到表单开始。 Edit the form like so:像这样编辑表单:

<form action="/clubreq" method="post">
    <% for (var i in clubreq){%>
        Club Name: <input type="text" name="clubname[]" value="<%= clubreq[i].clubname %>" /><br><br>
        Club Type: <input type="text" name="clubtype[]" value="<%= clubreq[i].type %>" /><br><br>
        <input type="submit" value="accept"/><br><br><hr>
    <%} %>
</form>

The important points being adding the action attribute indicating where to submit the form and the addition of inputs to ensure the values and transported with the form.重点是添加 action 属性,指示在哪里提交表单,并添加输入以确保值和表单一起传输。 If you don't like the way it looks, you can change the input type to hidden and then add another echo like you had before of club name and club type for the end user to see.如果您不喜欢它的外观,可以将输入类型更改为隐藏,然后像以前一样添加俱乐部名称和俱乐部类型的另一个回声,供最终用户查看。

Now on to how to access your form data server side, add the following to the top with all your other middleware:现在关于如何访问表单数据服务器端,将以下内容与所有其他中间件一起添加到顶部:

app.use(express.bodyParser());

Next, you can access the post data in your method like so:接下来,您可以像这样访问您的方法中的帖子数据:

app.post('/clubreq', function(req, res, next){
   // req.body object has your form values
   console.log(req.body.clubname);
   console.log(req.body.clubtype);
});

Hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM