nodejs Koa入门之URL路径处理与参数转码

在上一期中,我们处理http请求一律返回相同的HTML,这很明显不合理,如果我做个登录总不可能一直是一个界面吧。所以我们应该对不同的URL调用不同的处理函数,然后让他返回不同的结果。

const fs = require('fs'); // 文件模块
const Koa = require('koa');
const router = require('koa-router')(); // 处理url与express一样 都需要引入相关的处理模块
const bodyParser = require('koa-bodyparser'); // 处理原始请求json字符串解析模块
const app = new Koa(); // 实例化koa,K大写代表引入的是koa2
app.use(bodyParser()); // 注意中间件的加载先后顺序 否则当表单上传的时候会导致获取不到body的json数据 以及其他各种问题
app.use(router.routes()); // URL处理模块

app.use(async (ctx, next) => { // ctx 你可以理解为客户端 存储着所有的信息 username path 等信息
  console.log(ctx.request.path, 'asdsad'); // 获取浏览器地址信息 判断是否路径为/index
  if (ctx.request.path === '/index') {
    ctx.response.body = 'index page';  // 向客户端发送数据Index page
  } else {
    await next();
  }
});

// 其实上面的一行本身不是特别必须的 但是如哦参照app.use的方法又太蠢了,所以基于这个才出来了router这个东西
// 也不过是上面app.use的语法糖而已

app.use(async (ctx, next) => {
  // 获取客户端的请求方式与请求地址
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
  await next();
});

// router.get('/', async (ctx, next) => {
//   ctx.response.body = '<h1>Inde2额2额大苏打是的大苏打x</h1>';
// });
// 然后我们可以引入bodyParser 来对发送的数据进行解析编码
// 以下是一个简单地登录
router.get('/', async (ctx, next) => {

  // enctype 定义表单上传发送到服务器之前应该如何对表单数据进行编码 一共又三种 
  // application/x-www-form-urlencoded  在发送前编码所有字符(默认)
//   multipart/form-dat 不对字符编码 在使用包含文件上传控件的表单时,必须使用该值大半部分用于文件上传。
//   ext/plain  空格转换为 "+" 加号,但不对特殊字符编码。

  ctx.response.body = `<h1>Index</h1>
        <form action="/signin" method="post" enctype="application/x-www-form-urlencoded"> 
            <p>Name: <input name="name" value="koa"></p>
            <p>Password: <input name="password" type="password" value="123"></p>
            <p><input type="submit" value="Submit" name="submit"></p>
        </form>`;
});

// POst请求
router.post('/signin', async (ctx, next) => {
  // ctx.request.body的数据包含一整个由koa-bodyparser转化过来的对象 { name : koa,password: 1234}
  var
    name = ctx.request.body.name || '',
    password = ctx.request.body.password || '';
  console.log(`signin with name: ${name}, password: ${password}`);
  if (name === 'koa' && password == '1234') {
    ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
  } else {
    ctx.response.body = `<h1>Login failed!</h1>
        <p><a href="/">Try again</a></p>`;
  }
});
// 用router.get('/path', async fn)处理的是get请求。
// 如果要处理post请求,可以用router.post('/path', async fn)。
app.listen(2222);

以后的后续更新都会以注释加代码的形式进行更新~~~...