iKcamp|基于Koa2搭建Node.js实战(含视频)☞ HTTP请求

POST/GET请求——常见请求方式处理

🇨🇳 iKcamp 制做团队

原创做者:大哼阿干三三小虎胖子小哈DDU可木晃晃
文案校对:李益大力萌AuDDU小溪里小哈
风采主播:可木阿干AuDDU小哈
视频剪辑:小溪里
主站运营:给力xixty
教程主编:张利涛git


视频地址:www.cctalk.com/v/151143577…github

文章

Http 请求

在学习了 koa-router 以后,咱们就能够用它来处理一些常见的请求了,好比 POST/GETnpm


koa-router 提供了 .get.post.put.del 接口来处理各类请求,但实际业务上,咱们大部分只会接触到 POSTGET,因此接下来只针对这两种请求类型来讲明。小程序


当咱们捕获到请求后,通常都须要把请求带过来的数据解析出来。数据传递过来的方式通常有三种:微信小程序


请求参数放在 URL 后面

http://localhost:3000/home?id=12&name=ikcamp
复制代码

koa-router 封装的 request 对象,里面的 query 方法或 querystring 方法能够直接获取到 Get 请求的数据,惟一不一样的是 query 返回的是对象,而 querystring 返回的是字符串。浏览器

修改 app.js,咱们加入解析方式:微信

const Koa = require('koa')
  const router = require('koa-router')()
  const app = new Koa()

  router.get('/', async(ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
  })

  router.get('/home', async(ctx, next) => {
    console.log(ctx.request.query)
    console.log(ctx.request.querystring)
    ctx.response.body = '<h1>HOME page</h1>'
  })

  router.get('/404', async(ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
  })

  // add router middleware:
  app.use(router.routes())

  app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
  })
复制代码

运行代码,并经过浏览器访问 http://localhost:3000/home?id=12&name=ikcamp,而后打开控制台会看到下面的输出内容:app

{ id: '12', name: 'ikcamp' }
id=12&name=ikcamp
复制代码

请求参数放在 URL 中间

http://localhost:3000/home/12/ikcamp
复制代码

这种状况下,解析方式确定与上面的不同了,koa-router 会把请求参数解析在 params 对象上,咱们修改 app.js 文件,增长新的路由来测试下:koa

// 增长以下代码
  router.get('/home/:id/:name', async(ctx, next)=>{
    console.log(ctx.params)
    ctx.response.body = '<h1>HOME page /:id/:name</h1>'
  })
复制代码

运行代码,并经过浏览器访问 http://localhost:3000/home/12/ikcamp,而后查看下控制台显示的日志信息:async

{ id: '12', name: 'ikcamp' } 
复制代码

请求参数放在 body


当用 post 方式请求时,咱们会遇到一个问题:post 请求一般都会经过表单或 JSON 形式发送,而不管是 Node 仍是 Koa,都 没有提供 解析 post 请求参数的功能。


koa-bodyparser 说:『是时候登场了!』


首先,安装 koa-bodyparser 包:

npm i koa-bodyparser -S
复制代码

安装完成以后,咱们须要在 app.js 中引入中间件并应用:

const Koa = require('koa')
  const router = require('koa-router')()
  const bodyParser = require('koa-bodyparser')
  const app = new Koa()

  app.use(bodyParser())

  router.get('/', async(ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
  })

  router.get('/home', async(ctx, next) => {
    console.log(ctx.request.query)
    console.log(ctx.request.querystring)
    ctx.response.body = '<h1>HOME page</h1>'
  })

  router.get('/home/:id/:name', async(ctx, next)=>{
    console.log(ctx.params)
    ctx.response.body = '<h1>HOME page /:id/:name</h1>'
  })

  router.get('/404', async(ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'
  })

  app.use(router.routes())

  app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
  })
复制代码

而后咱们来试着写一个简单的表单提交实例。修改 app.js 增长以下代码,实现增长表单页面的路由:

// 增长返回表单页面的路由
  router.get('/user', async(ctx, next)=>{
    ctx.response.body = 
    ` <form action="/user/register" method="post"> <input name="name" type="text" placeholder="请输入用户名:ikcamp"/> <br/> <input name="password" type="text" placeholder="请输入密码:123456"/> <br/> <button>GoGoGo</button> </form> `
  })
复制代码

继续修改 app.js 增长以下代码,实现 post 表单提交对应的路由:

// 增长响应表单请求的路由
  router.post('/user/register',async(ctx, next)=>{
    let {name, password} = ctx.request.body
    if( name === 'ikcamp' && password === '123456' ){
      ctx.response.body = `Hello, ${name}!`
    }else{
      ctx.response.body = '帐号信息错误'
    }
  })
复制代码

常见的几种请求,以及相应的参数传递解析,咱们已经学习过了。下一节中,咱们会把项目整理重构下,作个分层,并引入视图层。

下一篇:代码分层——梳理代码,渐近于 MVC 分层模式

上一篇:iKcamp新课程推出啦~~~~~iKcamp|基于Koa2搭建Node.js实战(含视频)☞ 路由koa-router

推荐: 翻译项目Master的自述:

1. 干货|人人都是翻译项目的Master

2. iKcamp出品微信小程序教学共5章16小节汇总(含视频)


2019年,iKcamp原创新书《Koa与Node.js开发实战》已在京东、天猫、亚马逊、当当开售啦!

相关文章
相关标签/搜索