zoukankan      html  css  js  c++  java
  • ctx中的body无法找到

    学习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>`;
        }
        
    });
    
  • 相关阅读:
    1070 结绳
    1069 微博转发抽奖
    1068 万绿丛中一点红
    1067 试密码
    1066 图像过滤
    1065 单身狗
    CSS--文本溢出与换行
    css--滤镜filter
    css--flex布局
    css--table布局
  • 原文地址:https://www.cnblogs.com/xiaobaizitaibai/p/10784459.html
Copyright © 2011-2022 走看看