当我运行它时,它正确显示表单,但是当我点击提交按钮时,没有任何反应,帖子似乎不起作用! 我运行" nodemon index.js",并且chrome正确显示表单,但是当我单击提交按钮时,post方法handleform不会显示。
index.js
const Koa = require('koa');
const Router = require('koa-router'); //Use router instead of route
const router = new Router();
const bodyParser = require('koa-body');
const app = new Koa();
const Pug = require('koa-pug');
const pug = new Pug({
viewPath: './views',
basedir: './views',
app: app
});
app.use(bodyParser({
formidable: {uploadDir: './uploads'},
multipart: true,
urlencode: true
}));
router.get('/', renderForm);
router.post('/', handleForm);
async function renderForm(ctx,next) {
ctx.render('form');
await next();
}
async function handleForm(ctx) {
console.log("Submitted")
console.log(ctx.request.body);
console.lgo(ctx.req.body);
ctx.body = ctx.request.body;
}
app.use(router.routes()); //use router
app.listen(3000);
form.pug
html
head
title Form Tester
body
form(action="/", method="post")
div
label(for="say") Say:
input(type="text" name="say" value="Hi")
br
div
label(for="to") To:
input(type="text" name="to" value="Koa form")
br
input(type="submit" value="Send my greetings")
答案 0 :(得分:0)
我测试了你的代码。除了已经提到的console.lgo
问题之外,你的哈巴狗代码也是错误的。当检查浏览器中的页面源代码时,我有<form action="/" method="post"></form>
和所有输入字段,然后关闭表单标记。所以这是我的工作代码:
<强> index.js * 强>
const Koa = require('koa');
const Router = require('koa-router'); //Use router instead of route
const router = new Router();
const bodyParser = require('koa-body');
const app = new Koa();
const Pug = require('koa-pug');
const pug = new Pug({
viewPath: './views',
basedir: './views',
app: app
});
app.use(bodyParser({
formidable: {uploadDir: './uploads'},
multipart: true,
urlencode: true
}));
router.get('/', renderForm);
router.post('/', handleForm);
async function renderForm(ctx,next) {
ctx.render('form');
await next();
}
async function handleForm(ctx) {
console.log("Submitted")
console.log(ctx.request.body);
ctx.body = ctx.request.body;
}
app.use(router.routes()); //use router
app.listen(3000);
<强> form.pug 强>
html
head
title Form Tester
body
form(action="/", method="post")
div
label(for="say") Say:
input(type="text" name="say" value="Hi")
br
div
label(for="to") To:
input(type="text" name="to" value="Koa form")
br
input(type="submit" value="Send my greetings")