preface
The author chooses KOA as the Web framework, and will use two articles on Node.js programming interface and server-side rendering (SSR).
-
2 days quick start Node.js backend development 1- Interface
-
2 days quick Start Node.js backend development 2- Server rendering
Ps: Writing, content may change 😜
What is KOA?
Koa is a Web framework implemented based on Node.js. Is a lightweight framework, all functions through plug-ins.
👉 KOA Chinese www.koajs.com.cn
Besides KoA, there are many other Web frameworks for Node.js. The reason for choosing KOA is that it is easy to learn and fast to get started
- Express
- Nest
- Hapi
- Egg (based on KOA)
1. Preparation
🚧 node. js Version >= 10
Install KOA-Generator and KOA2 globally
npm install -g koa-generator koa2
Copy the code
The KOA-generator is a scaffolding for KOA that quickly generates project structure. Let’s see how it works. Okay
For example, 🌰
- Create a project named “vue-serve”
koa2 vue-serve
Copy the code
- Create a project named “vue-serve” and use
ejs
The template andsass
The CSS to compile
koa2 vue-serve -e -c sass
Copy the code
A comparison of the creation results of the two commands (just look 🤡)
Koa-generator Other parameters
parameter | use | |
---|---|---|
-e | Using the EJS template engine (puG by default) | ejs.bootcss.com |
–hbs | Use the HandleBars template engine | www.handlebarsjs.cn |
-H | Use the Hogan.js template engine | twitter.github.io/hogan.js |
-n | Use the Nunjucks template engine | nunjucks.bootcss.com |
-c | Specify the CSS compiler (less | stylus | compass | sass) (the default) using CSS | |
-f | Force the directory not to be empty |
* The template engine mentioned here is our server rendering engine
So let’s start with the practice
2. Create a project
Create a new project learn-pug
koa2 learn-Pug
Copy the code
Initialize the project
cd learn-Pug && npm i
Copy the code
Start the project
npm run start
Copy the code
Browser type http://localhost:3000, Hello Koa2! Indicates that the project is running successfully
The koA default port is 3000
3. Parsing process
The KOA-Generator generates the routes and template calls, so we just need to look at the routes and views folders.
process
- Routes are matched based on the url accessed
- Return data based on route or HTML using Pug
- The browser sees the result
💥 hot update
After NPM run start, the modified code can only be seen by restarting KOA
npm run dev
Copy the code
If an error occurs
'.' is not an internal or external command, nor is it a runnable program or batch file. ELIFECYCLE Command failed with exit code 1.Copy the code
Change the package.json to dev and run it again
"scripts": {
"dev": "nodemon bin/www",}Copy the code
Debug Node in Chrome
Add a line to package.json to run debug
"scripts": {
"debug": "nodemon --inspect bin/www",}Copy the code
Start debugging
npm run debug
Copy the code
-
Access any interface of localhost:3000
-
F12 Open developer tools
-
The Node icon is added to the left of Element (if not, wait or restart). Click to enter a new panel
-
Just open the debug file in the Sources option
4. Request
GET- Returns text
Open index.js, starting at line 9, and find this code
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
Copy the code
Access loclHost :3000/string and see koA2 string
The GET – return JSON
Open index.js, starting at line 13, and find this code
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
Copy the code
This time use the tool to request loclHost :3000/json
I use Hoppscotch (formerly Postwoman) you can also use other request tools, Postman, Apifox, ApiPost, etc
👉 making
Parameters of the GET –
Create a new GET request with parameters in index.js
// http://localhost:3000/get? size=100
router.get('/get'.async (ctx, next) => {
const { size } = ctx.query
ctx.body = 'Your size parameter is${size}`
})
Copy the code
Go to http://localhost:3000/get? size=100
GET- Route transmission parameter
Create a new GET request in index.js
// http://localhost:3000/get/koa
router.get('/get/:id'.async (ctx, next) => {
const { id } = ctx.params
ctx.body = 'Your ID parameter is${id}`
})
Copy the code
Parameters of the POST –
There is no POST request in the template. Create a new POST request in index.js
Request parameters: name and ID
router.post('/juejin'.async (ctx, next) => {
const { name, id } = ctx.body
ctx.body = {
name:'Your user name is${name}`.id: `${id}`,}})Copy the code
Request loclhost:3000/juejin with the tool
Request parameters:
{ "name":"Maokai"."id":1 } Copy the code
See the results
Other requests
The KOa-router also supports PUT, del, and All requests. For more information, see 👉Github
router
.put('/juejin/:id', (ctx, next) => {
// ...
})
.del('/juejin/:id', (ctx, next) => {
// ...
})
.all('/juejin/:id', (ctx, next) => {
// ...
});
Copy the code
5. Zi lu by
Once you know about index.js, open users.js
Subroutes are used to avoid writing all routes in a file, which simplifies maintenance
Line 3 indicates that all routes under the file have the /users prefix
router.prefix('/users')
Copy the code
/
= /users
/bar
= /users/bar
Reference child routes
After defining child routes, add references to app.js. Note lines 9 and 36
/ /...
const index = require('./routes/index')
const users = require('./routes/users')
// ...
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
Copy the code
After a route file is created, add it later
6. next
I haven’t explained what next is doing in the request, which involves koA’s Onion model
Used to change the execution order of middleware
Borrow a CSDN blogger’s chestnut 👉 original text
const one = (ctx, next) = > {
console.log('👉 one');
next();
console.log('<< one');
}
const two = (ctx, next) = > {
console.log('👉 two');
next();
console.log('<< two');
}
const three = (ctx, next) = > {
console.log('👉 three');
next();
console.log('<< three'); } app.use(one); app.use(two); app.use(three); 👉 one 👉 two 👉 three << three << two << oneCopy the code
The last
Learn how to write routing interfaces for vUE and React projects
Stay tuned for the next post…