我有一个表单,它动态地将来自用户的用户数据添加到表中。这是最后的表格外观
当其中一个使用这个帐户时,被按下,显示为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错误。
发布于 2020-08-16 13:34:25
您必须为表单设置一个默认操作,以使路由与post一起工作。如果您使用href,默认情况下它会执行get操作。
要在路由中发布一个帖子,您应该删除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>发布于 2020-08-16 13:26:10
/like是一个GET请求
对于POST请求,您需要使用/like/1,其中1可以是任何参数
https://stackoverflow.com/questions/63437368
复制相似问题