学习koa的时候看到廖雪峰大大的文章 其中有一段写的总是报错找不到name
代码如下
router.get('/', async (ctx, next) => { ctx.response.body = `<h1>Index</h1> <form action="/signin" method="post"> <p>Name: <input name="name" value="koa"></p> <p>Password: <input name="password" type="password"></p> <p><input type="submit" value="Submit"></p> </form>`; }); router.post('/signin', async (ctx, next) => { var name = ctx.request.body.name || '', password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `<h1>Welcome, ${name}!</h1>`; } else { ctx.response.body = `<h1>Login failed!</h1> <p><a href="/">Try again</a></p>`; } });
经过一番调试终于找到报错的原因 因为每个函数中少了
await next();
所以修改后的代码为
router.get('/', async (ctx, next) => { await next(); ctx.response.body = `<h1>Index</h1> <form action="/signin" method="post"> Name: <input name="name" value="koa"> Password: <input name="password" type="password"> <input type="submit" value="Submit"> </form>`; }); router.post('/signin', async (ctx, next) => { await next(); var name = ctx.request.body.name || '', password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `<h1>Welcome, ${name}!</h1>`; } else { ctx.response.body = `<h1>Login failed!</h1> <p><a href="/">Try again</a></p>`; } });