提问者:小点点

无法发布窗体NodeJS Express


我有一个表单,它动态地将用户数据添加到表中。这是最终的表单外观

当其中一个用户按下此帐户时,显示不能发布/喜欢

这是表格。我使用ejs

<form method="POST" autocomplete="off">
              <div class = "form-group col-sm-12">
                <label for="tagsarray">Enter Tags</label>
                <input type="text" class="form-control" id="likes" name="likes" aria-placeholder="Enter tags seperated by a comma">
                </div>
                <div class="form-group col-sm-7">
                  <label for="numberoftimes">Enter Number of Actions</label>
                <input type="text" class="form-control" id="action" name="action" aria-placeholder="Enter No. of Actions">
                </div>
                <% if (accounts) {%>
                  <table class = "striped">
                    <tbody>
                      <% accounts.forEach(accounts => { %>
                        <tr>
                          <td><a href="<% accounts._id %>"></a><%= accounts.title%></td>
                          <td><a href= "/like/<%= accounts._id%>"><button type="submit" class = "btn btn-primary col-auto" >Use this account</button></a></td>
                        </tr>
                        </tr>
                      <%});%>
                    </tbody>
                  </table>
                <%} else {%>
                  <p>You have no accounts added</p>
                <% } %>
            </form>

这是我的controller.js

control.get('/like', async(req, res) => {
    try{
        const accounts = await account.find({user: req.user.id}).lean()
        res.render("backend/like", {
            name: req.user.name,
            accounts
        });
    } catch(err) {
        console.log(err)
    }
    
});

control.post('/like/:id', getuserdata, (req, res, next) => {
    try{
        let title = res.accountuser.title;
        let pass = res.accountuser.password;
        let tags = req.body.likes;
        let actions = req.body.action;
        console.log(title, pass, tags, actions)
        iglike(title, pass, tags, actions)
        next();
        res.redirect('/like')
    }catch(err) {
        console.log(err)
    }
});

这不会捕捉到任何错误,控制台也不会显示任何内容。唯一的错误是无法POST/LIKE

这是getUserData函数以供参考

async function getuserdata(req, res, next) {
    let accountuser
    try{
        accountuser = await account.findById(req.params.id)
    } catch(err) {
        console.log(err)
    }

    res.accountuser = accountuser
    next()
};

我尝试了一个简单的type=submit按钮,但没有href,仍然显示相同的错误

请帮助我解决此无法发布/like错误。


共2个答案

匿名用户

您必须为您的表单设置一个默认操作,以使路由与POST一起工作。如果使用href,则默认情况下执行get。

要在路由中进行post,应该删除href并在表单中放置一个默认操作。

<form method="POST" autocomplete="off"  action="/like/<%= accounts._id%>">

然后在有提交按钮的行中,删除href(因为它从表单中移到了默认操作)

<td><button type="submit" class = "btn btn-primary col-auto" >Use this account</button></a></td>

匿名用户

/LIKE是GET请求

对于POST请求,您需要使用/like/1,其中1可以是任何参数