This is the 21st day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
Code [link 🔗]:(gitee.com/yang-yiming…) Continuously updated ~
Introduction to the
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.
The website address
Initialize the project
Generate package. Json
npm init
Copy the code
Installation of koa
npm install koa
Copy the code
New import file
Create a new SRC folder and create a mian.js (whatever you want to call it, like index.js).
const Koa = require('koa')
const app = new Koa()
app.use((ctx, next) = >{
ctx.body = 'hello'
})
const port = process.env.PORT || 8000
app.listen(port,() = >{
console.log(`server is running on ${port}`)})Copy the code
Nodesrc /main.js, in the browser access port,
The configuration file nodemon is automatically started
The installation
npm i nodemon
Copy the code
Adding a Startup Command
Package. json dev can also be replaced with something else
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."dev": "nodemon ./src/main.js"
},
Copy the code
Then run the command NPM run dev on the console to start. And when we change the code, it will automatically restart.
Reading configuration Files
Install dotenv
npm i dotenv
Copy the code
Create a new. Env file under the root directory (save some of the project configuration environment variables)
Then the newsrc/config/config.default.js
const dotenv = require('dotenv')
dotenv.config()
console.log(process.env.APP_PORT)
// Process node process
// env environment variable
module.exports = process.env
Copy the code
In the main. Js references
const Koa = require('koa')
// Deconstruct APP_PORT
const { APP_PORT } = require('./config/config.default')
const app = new Koa()
app.use((ctx, next) = > {
ctx.body = 'hello api'
})
app.listen(APP_PORT, () = > {
console.log(`server is running on ${APP_PORT}`)})Copy the code
Adding a Route Configuration
Installation of koa – the router
npm i koa-router
Copy the code
Take a look at the KOA-Router documentation
First go to the official website of NPMJS to check, fortunately, not written. npmjs
Never mind, let’s see if there is ✈️ on Github
Use steps:
- The import package imports the KOA-Router
const Router = require('koa-router')
Copy the code
- Instantiate an object
const indexRouter = new Router()
Copy the code
- Write the routing
indexRouter.get('/'.(ctx, next) = >{
ctx.body = 'hello index'
})
Copy the code
- Registered middleware
- Associate the router with the app and unregister the middle key with router.routes().
- Router is an object, but app.use() can only accept one function as an argument.
// must be a function
app.use(indexRouter)
app.use(indexRouter.routes())
Copy the code
Pull away from the outlet by file
If we have a class of UERS routes, we need to instantiate a new UserRouter, as well as the previous IndexRouter. It’s not a good way to write it all in main.js.
Create a Router folder to store various apis
router/user.route.js
const Router = require('koa-router')
const router = new Router({prefix:'/users'})
// concatenates with /users
router.get('/'.(ctx,next) = >{
ctx.body = 'hello users'
})
/ / export
module.exports = router
Copy the code
main.js
const Koa = require('koa')
const { APP_PORT } = require('./config/config.default')
const userRouter = require('./router/user.route')
const app = new Koa()
// must be a function
app.use(userRouter.routes())
app.listen(APP_PORT, () = > {
console.log(`server is running on ${APP_PORT}`)})Copy the code
Directory structure optimization
Purpose: To separate HTTP services from APP services
Create a new app file and create index.js under it to remove the instantiated objects in mian
const Koa = require('koa')
const userRouter = require('./router/user.route')
const app = new Koa()
// must be a function
app.use(userRouter.routes())
module.exports = app
Copy the code
main.js
const { APP_PORT } = require('./config/config.default')
const app = require('./app/index')
app.listen(APP_PORT, () = > {
console.log(`server is running on ${APP_PORT}`)})Copy the code
Then we realized that the error was reported because cutting the code from main.js directly to index.js involved changing the path level of the file reference.
const userRouter = require('.. /router/user.route')
Copy the code
Out of the controller
The handlers in route are split out
Create a new controller folder under it
user.controller.js
// Write as a class
class UserController{
async register(ctx, next){
ctx.body = 'User registered successfully'}}// Export the instantiated object
module.exports = new UserController()
Copy the code
user.route.js
const Router = require('koa-router')
/ / into the controller
const { register } = require('.. /controller/user.controller')
const router = new Router({prefix:'/users'})
// Register the interface
router.post('/register',register)
/ / export
module.exports = router
Copy the code
Use Postman to test it out