如何解决无法发布表单NodeJS Express
我有一个表单,可以动态地将用户的用户数据添加到表中。 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,actions)
next();
res.redirect('/like')
}catch(err) {
console.log(err)
}
});
这不会捕获任何错误,控制台绝对不会显示任何内容。唯一的错误是Cannot POST /like
。
这是getuserdata
函数供参考
async function getuserdata(req,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
错误。
解决方法
/ like是GET请求
对于POST请求,您需要使用 /喜欢/ 1 其中1可以是任何参数
,您必须为表单设置默认操作,才能使路由适用于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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。