ikcamp| build node. js combat (with video) based on KOA2? HTTP request

Source: Internet
Author: User

Post/get request--common request processing???? Ikcamp production Team

Original Big Hum, inspectable, 33, small tiger, fat, small ha, DDU, can wood, shake
Copy proofreading: Li Yi, vigorously Meng, Au, DDU, Creek, Xiao Ha
Style anchor: Can wood, inspectable, Au, DDU, Xiao Ha
Video clip: in the creek
Main station operation: To force XI, xty
Tutorial Editor: Zhang Litao

Video Address: https://www.cctalk.com/v/15114357765870

Article HTTP request

koa-routerafter learning, we can use it to handle some common requests, such as POST/GET .


koa-routerProvides .get , .post ,, .put and .del interfaces to handle various requests, but on the actual business, most of us are only exposed to POST and GET , so the next two types of requests are described.


When we capture the request, we generally need to parse the data that came with the request. There are generally three ways to pass data:


The request parameters are placed in the URLBehind
http://localhost:3000/home?id=12&name=ikcamp


koa-routerEncapsulated request object, the query method or method inside querystring can get directly to the Get requested data, the only difference is that the query object is returned, and querystring the return is a string.

Modify app.js , we add the parsing method:

  ConstKoa= require(' KOA ')ConstRouter= require(' Koa-router ')()ConstApp= New Koa()Router.Get('/', Async(CTX,Next= {    CTX.Response.Body = '   })Router.Get(' Home ', Async(CTX,Next= {    Console.Log(CTX.Request.Query)Console.Log(CTX.Request.QueryString)CTX.Response.Body = '   })Router.Get('/404 ', Async(CTX,Next= {    CTX.Response.Body = '   })//Add router middleware:  app. Use(Router.Routes())app.Listen( the,()= {    Console.Log(' server is running at http://localhost:3000 ')})


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

{ id: ‘12‘, name: ‘ikcamp‘ }id=12&name=ikcamp


The request parameters are placed in the URLMiddle
http://localhost:3000/home/12/ikcamp


In this case, the parsing method must be different from the above, the koa-router request parameters will be resolved on the params object, we modify the app.js file, add a new way to test:

  // 增加如下代码  router.get(‘/home/:id/:name‘,async(ctx, next)=>{    console.log(ctx.params)    ctx.response.body=‘  })


Run the code and access it through the browser http://localhost:3000/home/12/ikcamp , and then view the log information displayed under the console:


The request parameters are placed in the bodyIn


When post requested in a way, we encounter a problem: The post request is usually sent through a form or JSON form, and neither Node Koa , nor does it provide the ability to parse post the request parameters.


Koa-bodyparser said: "It's time to debut!" 』


First, install the koa-bodyparser package:

npm i koa--S


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

  ConstKoa= require(' KOA ')ConstRouter= require(' Koa-router ')()ConstBodyparser= require(' Koa-bodyparser ')ConstApp= New Koa()app. Use(Bodyparser())Router.Get('/', Async(CTX,Next= {    CTX.Response.Body = '   })Router.Get(' Home ', Async(CTX,Next= {    Console.Log(CTX.Request.Query)Console.Log(CTX.Request.QueryString)CTX.Response.Body = '   })Router.Get('/home/:id/:name ', Async(CTX,Next=>{    Console.Log(CTX.params)CTX.Response.Body = '   })Router.Get('/404 ', Async(CTX,Next= {    CTX.Response.Body = '   })app. Use(Router.Routes())app.Listen( the,()= {    Console.Log(' server is running at http://localhost:3000 ')})

Then let's try to write a simple form submission instance. Modify the app.js following code to increase the routing for the form page:

 //increase the route that returns the form page  router . get  ( '/user '   async  ( Ctx next) =>{ ctx .  Response . body  =   "  <form action= "/user/register" method= "post";   <input name= "name" type= "text" placeholder= "Please enter user name: Ikcamp"/>   <br/>   <input name= "password" type= "text" placeholder= "Please enter password: 123456"/>   <br/>   <button>gogogo</button>   </form>   " } ) 


Continue modifying app.js Add the following code to implement post the route for the form submission:

  //Increase the route that responds to form requests  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 '    }  })


Several common requests, as well as corresponding parameter-passing parsing, have been studied. In the next section, we'll refactor the project, make a hierarchy, and introduce the view layer.

Next: Code layering--grooming code, asymptotic MVC layered mode

Previous: Ikcamp new courses launched ~~~~~ikcamp| based on KOA2 to build node. js combat (including video)? Routing Koa-router

Recommendation: Translation Project Master's Readme: 1. Dry Goods | Everyone is a Master2 of translation projects. Ikcamp Small Program Teaching Total 5 Chapters 16 sections summary (including video)

ikcamp| build node. js combat (with video) based on KOA2? HTTP request

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.