[英]i cannot use the router.post method in node.js
我尝试在我的 node.js 应用程序中使用 post 请求,但由于某种原因我找不到它不起作用。 也许你能帮我解决这个问题
您可以在下面找到我的 report.js 和我的 report.ejs 文件:
report.js 文件:
var express = require('express');
var router = express.Router();
const { Pool, Client } = require("pg");
var app = express();
var bodyParser = require("body-parser");
/* GET home page. */
router.use(bodyParser.urlencoded({ extended : false }));
router.get('/', function(req, res, next) {
res.render('report', { title: 'Express' });
});
router.post('/top', function (req, res) {
console.log(req.body.todo + " is added to top of the list.");
res.redirect('/');
});
router.post('/bottom', function (req, res) {
console.log(req.body.todo + " is added to bottom of the list.");
res.json({ status: 'success' });
res.redirect('/');
});
module.exports = router;
report.ejs 文件:
<body>
<form>
<div class="form-group">
<label>To Do:</label>
<input type="text" class="form-control" name="todo">
</div>
<button type="submit" class="btn btn-primary btn-lg" formaction="/top" method="POST">Add to Top</button>
<button type="submit" class="btn btn-primary btn-lg" formaction="/bottom" method="POST">Add to Bottom</button>
</form>
<script src="/javascripts/reportjs.js"></script>
</body>
</html>
我收到两个按钮的错误消息:
GET /report 304 10.606 ms - -
GET /stylesheets/report.css 304 2.708 ms - -
GET /javascripts/reportjs.js 304 0.739 ms - -
GET /stylesheets/headder.css 304 1.229 ms - -
GET /bottom?todo=asdasd 404 2.253 ms - 145
Cannot GET /bottom
当我使用 POST 方法时,我不明白为什么应用程序使用 GET 方法
method
属性应该在<form>
标签上,而不是<button>
标签上。 默认方法是GET
所以这就是表单正在做的事情。 尝试这个:
<form method="POST">
<div class="form-group">
<label>To Do:</label>
<input type="text" class="form-control" name="todo">
</div>
<button type="submit" class="btn btn-primary btn-lg" formaction="/report/top">Add to Top</button>
<button type="submit" class="btn btn-primary btn-lg" formaction="/report/bottom">Add to Bottom</button>
</form>
或者你可以像这样在<button>
标签上使用formmethod
:
<form>
<div class="form-group">
<label>To Do:</label>
<input type="text" class="form-control" name="todo">
</div>
<button type="submit" class="btn btn-primary btn-lg" formaction="/report/top" formmethod="POST"">Add to Top</button>
<button type="submit" class="btn btn-primary btn-lg" formaction="/report/bottom" formmethod="POST">Add to Bottom</button>
</form>
在我看来,由于两个按钮都使用POST
因此将它放在<form>
标签上并避免重复会更好。
formaction
应该以/report/top
或/report/bottom
开头,因为页面的当前位置将在/report
并与之相关。 如果您只使用/top
或/bottom
它会丢失/report
位置的上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.