ctx中的body无法找到

学习koa的时候看到廖雪峰大大的文章 其中有一段写的总是报错找不到name

代码如下

router.get('/', async (ctx, next) => {
    ctx.response.body = `

Index

Name:

Password:

`; }); 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 = `

Welcome, ${name}!

`; } else { ctx.response.body = `

Login failed!

Try again

`; } });

 经过一番调试终于找到报错的原因 因为每个函数中少了

await next();
 
所以修改后的代码为
router.get('/', async (ctx, next) => {
    await next();
    ctx.response.body = `

Index

Name: Password:
`; }); 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 = `

Welcome, ${name}!

`; } else { ctx.response.body = `

Login failed!

Try again

`; } });

 

 

转载于:https://www.cnblogs.com/xiaobaizitaibai/p/10784459.html

你可能感兴趣的:(ctx中的body无法找到)