无法发布表单NodeJS Express

时间:2020-08-16 13:17:58

标签: node.js forms express post ejs

我有一个表单,可以动态地将用户的用户数据添加到表中。 This is the final form look

按下其中的使用此帐户之一时,将显示Cannot POST /like

这是表格。我使用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)
    }
});

这不会捕获任何错误,控制台绝对不会显示任何内容。唯一的错误是Cannot 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仍然显示相同的错误

请帮助我解决此Cannot POST /like错误。

2 个答案:

答案 0 :(得分:0)

/ like是GET请求

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

答案 1 :(得分:0)

您必须为表单设置默认操作,才能使路由适用于post。如果您使用href,则默认情况下会获取。

要在路线中发布信息,应删除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>
相关问题