当前位置:网站首页>Koa2 learning and using
Koa2 learning and using
2022-06-29 23:57:00 【Yangxiaoao】
This article mainly uses koa2 Learn to build a back-end project
Koa2
One 、Koa2 install
Create a blank Directory , And then go to the terminal , And on the terminal koa Installation :
# Project initialization
npm init -y
# install koa2
npm i koa2 -S
# install nodemon
npm i nodemon -D
Two 、 Entrance file
Create in project root app.js file , And generated in the previous operation package.json Internal configuration :
{
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "nodemon app.js"
},
}
stay app.js in :
const Koa = require('koa2');
const app = new Koa();
const port = 9000;
/* Explain the following code : app.use() The method is : Add the given middleware method to this application . To put it simply, call the middleware app.use() return this, So it can be expressed in a chain */
app.use(async (ctx)=>{
ctx.body = "Hello, Koa";
// ctx.body yes ctx.response.body Abbreviation
})
app.listen(port, ()=>{
console.log('Server is running at http://localhost:'+port);
})
And then run npm run start , And enter... In the browser http://localhost:9000/ You can see the page effect .
Tips :
For future port and IP Convenient management , In fact, we can transform IP Export with port in one file , Then import to use , This makes it easy to manage :
// Production environment :http://xxx.com Development environment domain name :http://localhost const host = "http://localhost"; // Production environment port : Customize Development environment domain name :9000 const port = 9000; module.exports = { host, port }
And then to app.js Or you need to use IP And port file import :
const { host, port} = require("./utils") app.listen(port, ()=>{ console.log(`Server is running at ${ host}:${ port}`); })
3、 ... and 、 Onion model
learn Koa You have to understand Onion model :
Koa and Express Will use middleware ,Express The middleware is executed sequentially , From the first middleware execution to the last middleware , Respond :
Koa It starts from the first middleware , encounter next Go to the next middleware , Until the last middleware , In reverse order , Execute the previous middleware next Later code , The response is not sent until the end of the first middleware execution .
For this onion model , Let's explain it in code . If the above code is rewritten into :
const Koa = require('koa2');
const app = new Koa();
const port = 9000;
app.use(async (ctx, next)=>{
console.log(1)
await next();
console.log(2)
})
app.use(async (ctx, next)=>{
console.log(3)
await next();
console.log(4)
})
app.use(async (ctx)=>{
console.log(5)
})
app.listen(port, ()=>{
console.log('Server is running at http://localhost:'+port);
})
After the browser is refreshed , The order the console gets is :
1
3
5
4
2
Now you can see , We go through next You can run the next middleware first , When the middleware is finished , Continue to run the current next() Later code .
Four 、 Route installation
When you need to match different routes , Can install :
npm i koa-router
take app.js modify :
const Koa = require('koa2');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
const port = 9000;
router.get('/', async (ctx)=>{
ctx.body = " The root path ";
})
router.get('/manage', async (ctx)=>{
ctx.body = " Management interface ";
})
app.use(router.routes(), router.allowedMethods());
app.listen(port, ()=>{
console.log(`Server is running at http://localhost:${
port}`);
})
here , Refresh to the browser and add... At the end of the address bar /manage You can get the contents of the root path and the list module .
remarks :
// call router.routes() To assemble a matched route , Return a merged middleware
// call router.allowedMethods() Get a middleware , When a non-conforming request is sent , Returns the `405 Method Not Allowed` or `501 Not Implemented`
allowedMethods Method can be configured as follows :
app.use(router.allowedMethods({
// throw: true, // Throw an error , Instead of setting the response header status
// notImplemented: () => ' The function required by the current request is not supported ',
// methodNotAllowed: () => ' Unsupported request mode '
}))
5、 ... and 、 Route splitting
When the project is large , When there are many routes , We need to divide the modules . here , You need to split the route . The back end of this project should serve Web Official website and background management system , So we divide the routing into two modules :web And manage.
1、 establish router Folder
establish router Folder , And create :index.js ( Route master entry file )、manage/index.js (manage Module route entry file )、web/index.js (web Module route entry file ):
// app.js
const Koa = require("koa2");
const router = require("./router")
const app = new Koa();
const port = 9000;
// call router middleware
app.use(router.routes(), router.allowedMethods());
app.listen(port, ()=>{
console.log(`Server is running at http://localhost:${
port}`);
})
// index.js
const Router = require("koa-router");
const manage = require("./manage");
const web = require("./web");
const router = new Router();
router.get("/", async ctx=>{
ctx.body = " The root path "
})
router.use("/manage", manage.routes(), manage.allowedMethods());
router.use("/web", web.routes(), web.allowedMethods());
module.exports = router;
// manage/index.js
const Router = require("koa-router")
const router = new Router();
router.get('/', async ctx=>{
ctx.body = " Management system "
})
module.exports = router;
// web/index.js
const Router = require("koa-router")
const router = new Router();
router.get('/', async ctx=>{
ctx.body = " Official website "
})
module.exports = router;
To browser refresh localhost:9000/manage And localhost:9000/web You can get manage and web The data returned by the two modules .
2、 Route redirection
Well, some students will ask , If I want to go directly from localhost:9000 Redirect to localhost:9000/home What should I do ?
We can do it in router/index.js Do the following configuration in :
router.use('/home', home.routes(), home.allowedMethods());
...
router.redirect('/', '/home');
3、404 Invalid route
If an invalid route is accessed , Then we can return to 404 page :
stay router Next errorPage.js :
const Router = require('koa-router');
const errorPage = new Router();
errorPage.get('/', async (ctx) => {
ctx.body = " The access page does not exist ";
})
module.exports = errorPage;
stay router/index.js in :
const errorPage = require("./errorPage")
// 404 Page routing
router.use("/404", errorPage.routes(), errorPage.allowedMethods());
stay app.js I quote :
// Jump to all pages that do not match 404
app.use(async (ctx, next) => {
await next();
if (parseInt(ctx.status) === 404) {
ctx.response.redirect("/404")
}
})
app.use(router.routes(), router.allowedMethods());
6、 ... and 、 The backend allows cross domain
The front end wants to cross domain , You can set proxy. If the backend allows cross domain , You can do the following :
// install koa2-cors
$ cnpm i koa2-cors
// introduce koa2-cors middleware
const cors = require("koa2-cors");
// here cors Middleware must be written before routing
app.use(cors());
app.use(router.routes(), router.allowedMethods())
7、 ... and 、 Read static resource file
First installation koa-static, The command line code is as follows :
yarn add koa-static
Then create... In the root directory of the project assets after , Add picture resources ( Take a picture of yourself ) Folder images Put it in it . We assume that 404 The page needs to return an error warning graph , Can be in app.js Do the following :
// introduce
const path = require('path')
const static = require('koa-static')
// Get static resource folder
app.use(static(path.join(__dirname, '/assets')));
...
app.use(router.routes(), router.allowedMethods())
Suppose there is a picture called 404.gif, So let's open the browser , visit :http://localhost:9000/images/404.gif You can get the picture . Note here :
There is no need to write on the path assets, Because we have specified that when accessing resources , http://localhost:9000 Auto point assets Folder . thus , We know that the address of the image in the database only needs to be filled in
/images/404.gifthat will do .
If we want to open 404 The page shows this picture , You need to do the following steps :
#1、 install mime-types
$ npm i mime-types
2、 Use fs Read the file
modify errorPage.js:
const Router = require("koa-router")
const router = new Router();
const fs = require("fs")
const path = require("path")
const mime = require("mime-types")
router.get('/', async ctx=>{
const filePath = path.join(__dirname, "../assets/images/404.gif");
const file = fs.readFileSync(filePath); // Read the file
const mimeType = mime.lookup(filePath) // Read file type
ctx.set("content-type", mimeType); // Set the return type ( This is an important step )
ctx.body = file; // Back to picture
})
module.exports = router;
边栏推荐
- Buffer flow exercise
- The role of VMware virtual machine
- After crossing, she said that the multiverse really exists
- Create an API rapid development platform, awesome!
- 一步步教你在Edge浏览器上安装网风笔记
- High performance and high availability computing architecture of "microblog comments" in microblog system
- 漫画安全HIDS、EDR、NDR、XDR
- Divisor
- 深度学习的历史
- History of deep learning
猜你喜欢

Create an API rapid development platform, awesome!

Halcon实用:焊点检出设计思路

Use of jetpack's room in combination with flow

Construction of module 5 of actual combat Battalion

Cartoon security HIDS, EDR, NDR, XDR

Basic tutorial for installing monggodb in win10

剑指 Offer 14- II. 剪绳子 II
500 error occurred after importing skins folder into solo blog skin

What is IGMP? What is the difference between IGMP and ICMP?

After working in the software development industry for six years, I changed my ideas in those years
随机推荐
Exploration and Practice on the future direction of byte cloud database
Teach you step by step to install webwind notes on edge browser
Golang泛型的巧妙应用,防止变量空指针错误,防止结构体字段空指针错误
On binary tree
How about counting Berry Pie 4? What are the possible ways to play?
我想知道今天还可以开户么?另外想问,现在在线开户安全么?
Solr basic operation 5
Overseas digital authentication service provider advance AI was selected into the "2022 brand sea Service Market Research Report" of equalocean
6.28 problem solving
500 error occurred after importing skins folder into solo blog skin
FPGA开发(2)——IIC通信
Bee common configuration
The role of VMware virtual machine
Golang6 reflection
High performance and high availability computing architecture of "microblog comments" in microblog system
Leetcode(633)——平方数之和
剑指 Offer 14- II. 剪绳子 II
Simple understanding of B tree and b+ tree
Digital collection of cultural relics, opening a new way of cultural inheritance
西门子低代码 9.14版本: 满足不同需求


