POST/GET requests – Common request processing

IKcamp Production team 🇨🇳

Original author: Dahum, Gan, SAN SAN, Tiger, Fatty, Ha, DDU, Kwood, Wobble Copy proofreading: Li Yi, Da Li Meng, Au, DDU, Brook, Ha Style Anchor: Kwood, Gan, Au, DDU, Ha Video clip: Brook main station operation: Geili XI, XTY tutorial editor: Zhang Li Tao


Video address: www.cctalk.com/v/151143577…

The article

The Http request

Now that we have learned about the KOA-Router, we can use it to handle common requests, such as POST/GET.


The KOA-Router provides.get,.post,.PUT, and.del interfaces to handle various requests, but in practice, most of us will only deal with POST and GET, so we will focus on these two request types only.


When we capture a request, we usually need to parse the data that the request brought in. There are three ways in which data can be transmitted:


Request parameters are placed inURLbehind

http://localhost:3000/home?id=12&name=ikcamp
Copy the code


The koa-Router encapsulates a Request object. A query or queryString method can retrieve the data from a Get request. The only difference is that query returns an object while QueryString returns a string.

To modify app.js, we add parsing:

  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')})Copy the code


Run the code, and through the browser to http://localhost:3000/home? Id =12&name=ikcamp, then open the console and see the following output:

{ id: '12', name: 'ikcamp' }
id=12&name=ikcamp
Copy the code


Request parameters are placed inURLIn the middle

http://localhost:3000/home/12/ikcamp
Copy the code


In this case, the router will parse the request parameters to the params object. We will modify the app.js file and add a new route to test it:

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


Run the code, and through the browser to access http://localhost:3000/home/12/ikcamp, then look at the console display of log information:

{ id: '12', name: 'ikcamp' } 
Copy the code


Request parameters are placed inbody


When making post requests, we run into a problem: Post requests are usually sent as forms or JSON, and neither Node nor Koa provides the ability to parse THE parameters of the POST request.


Koa-bodyparser says, “It’s time to show up!”


First, install the KOA-BodyParser package:

npm i koa-bodyparser -S
Copy the code


After the installation is complete, we need to introduce middleware in app.js and apply:

  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')})Copy the code

Then let’s try to write a simple form submission instance. Modify app.js to add the following code to add the routing of the form page:

  // Add a route back to the form page
  router.get('/user'.async(ctx, next)=>{
    ctx.response.body = 
    
      




}) Copy the code


Add the following code to app.js to implement the route corresponding to post form submission:

  // Add a route that responds to the form request
  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 = 'Account information error'}})Copy the code


We have already studied several common requests and the corresponding parameter passing parsing. In the next section, we will reorganize the project into a layer and introduce a view layer.

Next: Code Layering – Comb through code, moving closer to the MVC layering pattern

~~~~~iKcamp | KoA2-based Node.js framework ☞ Route KOa-router

Translation project Master:

1. Dry goods | Everyone is the Master of translation project

2. IKcamp produces a total of 5 chapters and 16 sections of wechat mini program teaching (video included)


In 2019, iKcamp’s original new book Koa and Node.js Development Actual Combat has been sold on JD.com, Tmall, Amazon and Dangdang!