background
Recently want to develop a team work management background to improve work efficiency, need to add, delete, check and change data, learn to write their own interface is essential, and Node.js is more suitable for the front-end start of a server-side development, based on node.js platform has a small and beautiful Web development framework Koa, now we learn.
What is KOA?
Node.js is a javascript runtime environment based on the Chrome V8 engine, while Koa is the next generation Web development framework based on the Node.js platform.
Koa’s advantage?
Koa is a new Web framework, built by the same people behind Express, that aims to be a smaller, more expressive, and more robust cornerstone of web application and API development. By making use of async functions, Koa helps you discard callback functions and greatly enhances error handling. Koa does not bundle any middleware, but rather provides an elegant way to help you write server-side applications quickly and happily.
Here is the comparison between Express and Koa:
I prefer Koa to Express because it is lightweight and flexible, and you can develop your own middleware and build your own projects from zero to one.
The framework | Making attention | To fit the difficulty | advantages | disadvantages | grammar |
---|---|---|---|---|---|
Express | 53.2 k. | simple | Feature rich, out of the box | The framework has heavy, multi-layer nested callbacks | ES5 |
Koa | 31.2 k. | simple | Lightweight, flexible and simple | Relatively small community | ES6 and ES7 |
Start the installation
1. Environment configuration
Koa depends on Node V7.6.0 or ES2015 and later and async method support. If Node version is earlier than 7.6.0, please upgrade Node version. If the project depends on different versions of Node.js, you can use the Node.js version management tool NVM to switch the required version of the current project.
2. Initialize package.json
You can view configuration file information to manage various NPM packages. The initial packge name cannot be the same as the Koa name; otherwise, an error message will be displayed during Koa installation.
/ / initialization
$ npm init
Copy the code
3. Install Koa
/ / installation of koa
$ npm install koa 或 cnpm install koa
Copy the code
4. Check whether the installation is successful
If no error is reported and the version number is displayed, the installation is successful.
// Check the KOA version number
$ koa -V
Copy the code
Koa related API
Here are a few of the apis used in the following examples, more of which can be found in the official documentation
I. Application
app.use(function)
Adds the given middleware method to the application
app.context
App.context is the prototype from which to create CTX. You can add additional properties to CTX by editing app.context
App. Listen (…).
Bind a port as a program entry
Context:
ctx.req
Node request object
ctx.request
Koa request object
ctx.url
Get the URL? Query parameters later
ctx.method
Get request type
3. Request
request.querystring
According to the? Gets the raw query string
request.query
Gets the parsed query string, and returns an empty object when there is no query string
4. Response
response.body
Get the response body
Write a Hello World by hand
Add hello.js file and write the following code:
// hello.js
const Koa = require('koa')
const app = new Koa()
app.use((ctx) = > {
// CTX is the Context object provided by KOA, which represents the Context of this session such as request, response, etc
ctx.response.body = 'hello world'
})
// Use port 3000 to listen
app.listen(3000.() = > {
console.log('server is running at http://localhost:3000')})Copy the code
// Run the js file $node test.jsCopy the code
Write a get request by hand
First of all, we need to know that there are two kinds of data that get obtains from the request, and two kinds of parameter formats are accepted, as follows:
I. Method of obtaining request:
Use one of these
- 1. Obtain ctx.request.query from the request object in context (CTX)
- Query (ctx.query.query)
Ii. Receiving parameters:
- 1. Receive the well-formatted JSON object ctx.request.query
- 2. Receive the string ctx.request. Querystring
Create a new get.js file and write the following code:
// get.js
const Koa = require('koa')
const app = new Koa()
app.use( async (ctx) => {
let url = ctx.url
// 1, from the context (CTX) request object
let request = ctx.request
let req_query = request.query
let req_querystring = request.querystring
// 2. Access from context (CTX)
// let ctx_query = ctx.query
// let ctx_querystring = ctx.querystring
ctx.body = {
code: "000001".desc: "success".data: {
url,
req_query,
req_querystring,
// ctx_query,
// ctx_querystring
}
}
})
app.listen(3000.() = > {
console.log('server is running at http://localhost:3000')})Copy the code
After running the project, open the following address:
http://localhost:3000/?age=18&name=jason
/ / interface to return the result as follows: {" code ":" 000001 ", "desc" : "success", "data" : {" url ":" /? age=18&name=jason","req_query":{"age":"18","name":"jason"},"req_querystring":"age=18&name=jason"}}Copy the code
Write a post request
For POST requests, Koa does not encapsulate the method of obtaining parameters. Instead, it needs to parse the POST form data into a Query String by parsing the Node request object req in the context, and then parse the Query String into JSON format.
Create a new post.js file and write the following code:
// post.js
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx) => {
if (ctx.url === '/' && ctx.method === 'GET') {
// Return the form page when a GET request is made
let html = ' Post request example:
ctx.body = html
} else if (ctx.url === '/' && ctx.method === 'POST') {
// When a POST request is made, the data in the POST form is parsed and displayed
let postData = await parsePostData(ctx)
ctx.body = {
code: "000001".desc: "success".data: postData
}
} else {
// Other requests show 404
ctx.body = '<h3>404</h3>'}})// Parse the POST parameter of node's native request in context
function parsePostData(ctx) {
return new Promise((resolve, reject) = > {
try {
let postdata = "";
ctx.req.addListener('data'.(data) = > {
postdata += data
})
ctx.req.addListener('end'.function() {
let parseData = parseQueryStr(postdata)
resolve(parseData)
})
} catch (err) {
reject(err)
}
})
}
// Parse the POST request parameter string into JSON format
function parseQueryStr(queryStr) {
let queryData = {}
let queryStrList = queryStr.split('&')
console.log(queryStrList)
for ( let [index, queryStr] of queryStrList.entries() ) {
let itemList = queryStr.split('=')
queryData[itemList[0]] = decodeURIComponent(itemList[1])}return queryData
}
app.listen(3000.() = > {
console.log('server is running at http://localhost:3000')})Copy the code
After running the project, open the following address to enter the form information and submit it:
http://localhost:3000/
/ / interface to return the result as follows: {" code ":" 000001 ", "desc" : "success", "data" : {" name ":" name ", "age" : "18"}}Copy the code
The last
This article belongs to the entry, for any knowledge is the first entry, and then in-depth, I hope to help you!