One, foreword
For starters, though, a scaffold like the KOA-Generator is the fastest way to start a KOA2 or Node project. However, building your own project is more suitable for the customized business scenario where the front end is separated from the back end in actual development, and allows us to focus not only on the development itself, but also to know what it is and get more out of it.
Install the KOA dependencies globally (keeping the project version consistent) or locally in the project
npm install -g koa
npm install koa --save
Copy the code
Create project & install dependencies
Create the file and initialize the project
npm init
Copy the code
2. Install dependencies
NPM install koa-router koa-bodyParser --save // Hot restart NPM install nodemon --save // support import module import NPM install Babel-plugin-transform-es2015-modules-commonjs babel-register --save // mongodb NPM install mongoose --save // resolve cross-domain problems npm install koa2-cors --saveCopy the code
Three, configuration,
1. Basic configuration
The basic development environment is set up. Enable service to listen on port 3000:
For any request, app will call the asynchronous function app.use(async (CTX, next) => {}) to process the request, and only after next() can the next app.use() be executed.
Const Koa = require(' Koa ') const app = new Koa({// proxy // proxy: true}); // logger app.use(async (ctx, next) => { console.log('--0-0--') await next(); const rt = ctx.response.get('X-Response-Time') console.log(`--0-1-- ${ctx.method} ${ctx.url} - ${rt}`) }) // x-response-time app.use(async (ctx, next) => { console.log('--1-0--') const start = new Date() await next() const ms = Date.now() - start; console.log('--1-1--') ctx.set('X-Response-Time', `${ms}ms`); }) // response app.use(async ctx => { ctx.body = 'Hello World, Koa! ' }) app.listen(3000)Copy the code
2. Configure routes
const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const app = new Koa(); app.use(bodyParser()); // request body const router = require('koa-router')() router. Get ('/', async (CTX, next) => { // todo }) app.use(router.routes()); app.listen(3000); console.log('app started at port 3000... ')Copy the code
You can directly access port 3000. If you develop an aggregation interface for the BFF layer, you can add an API prefix to identify it
const Router = require('koa-router')
const router = new Router({
prefix: '/api'
})
Copy the code
At this time access address to: http://localhost:3000/api
3. Hot restart processing
Hot updates and code modifications to standard Webpack projects can be seen in real time without restarting the NPM run start project. For node project management, of course, there is a similar tool: Nodemon
Nodemon, used to monitor any changes in the source and automatically restart the server. You can customize nodemon.json
Change package.json and execute NPM run start to achieve a hot restart
// package.json
"scripts": {
...
"start": "nodemon app.js"
},
Copy the code
4. Node supports import module (negligible)
Native Node does not support import import modules, so imposing import in a project will throw an error like SyntaxError: Unexpected Token import
The solution involves the following aspects:
- The installation
babel
Rely on - Create it in the root directory
start.js
- To change the
package.json
Install the following dependencies
npm install babel-plugin-transform-es2015-modules-commonjs babel-register --save
Copy the code
Create start.js in the root directory
require('babel-register')
(
{
plugins: ['babel-plugin-transform-es2015-modules-commonjs'],
}
)
module.exports = require('./app.js')
Copy the code
To change thepackage.json
"scripts": {
...
"start": "nodemon star.js"
}
Copy the code
Complete the above three steps, use import syntax in app.js, and run NPM start
5. Connect to the database
- Installation:
npm install mongoose --save
- Activation:
mongod
- View Management:
MongoDB Compass
A. Set up the following databases:
B. Query statements
// 文件路径: app/dbHelper/user.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// mongoDB
const dbUrl = "mongodb://localhost:27017/testLocal";
const client = new MongoClient(dbUrl, {useNewUrlParser: true});
const dbName = 'testLocal'
const tableName = 'user'
/**
* @desc: 查询所有用户
*/
exports.queryUsers = function() {
return new Promise(function (resolve, reject) {
try {
client.connect(function(err) {
assert.equal(null, err);
const db = client.db(dbName);
const collection = db.collection(tableName);
collection.find({}).toArray(function(err, result) {
assert.equal(err, null);
// console.log('--db-1-result--', result)
client.close();
resolve(result)
});
})
} catch(e) {
reject(e)
}
})
}
Copy the code
C. Run the program to view the result
Data query results:
View result:
So far, the project structure of gathering BFF layer interface function is basically satisfied.
6, resolve cross-domain
For cross-domain interface, there are many solutions, such as JSONP, CROs, Nginx proxy, Node proxy, etc. Only the CROS scheme is described here: KOA2-CORS
Entrance to the file
// app.js introduces const cors = require('koa2-cors') const app = new Koa() import corsConfigs from './configs/cors' // handles cross-domain configuration app.use(cors(corsConfigs));Copy the code
The configuration file
// config/ cers. js /** * @desc: cross-domain processing configuration item * @author: @date: 2021-02-24 ** / const corsConfigs = {exposeHeaders: ['WWW-Authenticate', 'Server-Authorization', 'Date'], maxAge: 100, credentials: true, allowMethods: ['GET', 'POST', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'Accept', 'X-Custom-Header', 'anonymous'], } export default corsConfigsCopy the code
TS & ESLint
To complement…
Can collect obsidian (SUN) SITE 🌝, timely access to the article update information
Five,Project
chart
├ ─ ─ app │ ├ ─ ─ controller │ │ └ ─ ─ the user. The js │ ├ ─ ─ dbHelper │ │ └ ─ ─ the user. The js │ └ ─ ─ the router. The js ├ ─ ─ app. Js ├ ─ ─ configs │ └ ─ ─ ├─ package.json ├─ download.txt ├─ download.txt ├─ download.txtCopy the code
Source reference
GitHub Repository: github.com/lianpf/exam…
The key file
app.js
/** * @desc: import file * @author * @date: 2021-02-24 ** / const Koa = require(' Koa '); const bodyParser = require('koa-bodyparser') const cors = require('koa2-cors') const app = new Koa() import router from './app/router' import corsConfigs from './configs/cors' // Logger middleware/ / const loggerAsync = require('./middleware/ loggerAsync ') // app.use(loggerAsync()) // router app.use(bodyParser()); // Parse the request's body app.use(router.routes()); // response // app.use(async ctx => { // ctx.body = 'Hello World, Koa! '//}) // Listen on port 3000: app.listen(3000); console.log('app started at port 3000... ')Copy the code
package.json
{"name": "koa2-ts-mongodb", "version": "1.0.0", "description": "koa2-mongodb-ts demo", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon start.js" }, "author": "", "license": < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; word-break: inherit! Important;" "^ 6.26.0 koa", "" :" tokens ^ 2.13.1 ", "koa - bodyparser" : "^ 4.3.0", "koa - the router" : "^ 10.0.0", "koa2 - cors" : "^ 2.0.6", "mongoose" : "^ 5.11.18 nodemon", ""," ^ 2.0.7 "}, "devDependencies" : {" @ types/koa ":" ^ 2.13.0 ", "tslint" : "^ also 6.1.3", "typescript" : "^ 4.1.5}}"Copy the code
start.js
require('babel-register')
(
{
plugins: ['babel-plugin-transform-es2015-modules-commonjs'],
}
)
module.exports = require('./app.js')
Copy the code
app/router.js
const router = require('koa-router')()
const User = require('./controller/user')
router.get('/', User.query)
export default router
Copy the code
Finally, I hope you can realize the great dream of becoming a front-end master as soon as possible! Welcome to exchange ~
- Wechat official account: Mr. Lian has cat disease
- Nuggets: Obsidian
- Personal blog: lianpf.github. IO /
Copyright of this article belongs to original author yao Ling all! Without permission, is strictly prohibited! To the illegal carrier, the original author reserves the right to pursue legal means! If you need to reprint, please contact wechat public number: Mr. Lian has cat disease, you can get the author’s contact information!