I believe this will be useful for those who want to get started writing NodeJS, so let’s start our main topic (instead of using KOA-Generator scaffolding here, we will directly build the project ourselves, which is suitable for front and back end separation).
One: Create the project
Koa dependencies can be installed globally (maintaining project version uniformity)
npm install -g koa
Copy the code
Or install it in our local project
npm install koa --save
Copy the code
Now that we have the basic development environment set up, we can start our KOA journey:
const Koa = require('koa'); const app = new Koa(); // For any request, app will call this asynchronous function to handle the request: app.use(async (CTX, next) => {await next(); // todo }); app.use(async (ctx, next) => { await next(); // todo }); // Listen on port 8081: app.listen(8081);Copy the code
Use (async (CTX, next) => {}), the next app.use() can only be executed after next(), so koA-Router is introduced here
Add a route
npm install koa-router koa-bodyparser --save
Copy the code
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(9000);
console.log('app started at port 9000... ')
Copy the code
So go directly to http://localhost:9000 and you can access it
You can also prefix your routes
const Router = require('koa-router')
const router = new Router({
prefix: '/api'
})
Copy the code
So you just need to visit http://localhost:9000/api, and we write our interfaces, the prefix is not less.
3. Processing hot restart
Every time we make a change we have to close the program and then NPM start. It’s nice to remember that webpack is hot and want to build with Webpack. Nodemon is a utility that monitors any changes in the source and automatically restarts the server. It also supports custom configuration of nodemon.json here do not do configuration, direct use
npm install nodemon --save
Copy the code
Modify the package. The json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."start": "nodemon app.js"
},
Copy the code
Run NPM start, and you’ll have a hot restart and be happy to develop
Support the import module
Because the current native node does not support importing modules, if you import modules, you will get the following error:
At this point we 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
Modify package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."start": "nodemon star.js"
},
Copy the code
Run NPM Start directly, and you can see that our project already supports import syntax
V. Connect mongodb and Mongoose
Here do not do mongodb installation tutorial, friends can first go to install mongodb, after the installation, see the following picture that the installation and startup is successful
npm install mongoose --save
Copy the code
Next, I will use a simple and violent method to connect to our database mongodb, here for the sake of aspects to let you understand, do not do hierarchical processing and file processing (the actual project to do this estimate is not to add pay oh)
Add in app.js
const db = mongoose.connect("mongodb://localhost/testDB"Var UserSchema = new mongoose.Schema({username:String, password:String, email:String}); var User = mongoose.model('User',UserSchema); Var user = {username:'ydj',
password: '123123',
email: ' '
}
var newUser = new User(user);
newUser.save();
router.get('/', async (ctx, next) => {
let val = null
const data = await User.findOne({username: 'ydj'})
console.log('data', data)
const result = {
code:200,
response: data,
ts: 12345
}
ctx.response.body = result
return result
})
Copy the code
Create a new data model for the user and add the user data to our testDB database. When we access localhost:9000, we request our database and return the data. As you can see from the diagram above, we didn’t have the users collection to start with. When we run the program, our database will automatically add the users collection and data:
After running:
Solve cross-domain
Finally, when we write the interface to provide others, the cross-domain problem must be solved, koA side is also easy to deal with, providing KOA2-CORS processing
npm install koa2-cors --save
Copy the code
const cors = require('koa2-cors')
app.use(cors({
exposeHeaders: ['WWW-Authenticate'.'Server-Authorization'.'Date'],
maxAge: 100,
credentials: true,
allowMethods: ['GET'.'POST'.'OPTIONS'],
allowHeaders: ['Content-Type'.'Authorization'.'Accept'.'X-Custom-Header'.'anonymous']}));Copy the code
For koA2-CORS other related configuration, you can search online
7. To summarize
Project directory structure
├ ─ ─ node_modules dependent package ├ ─ ─ routes routing | ├ ─ ─ index. The js | ├ ─ ─ the user. The js ├ ─ ─ app. The main entry of js file ├ ─ ─ start. Js processing import configuration file └ ─ ─ package.jsonCopy the code
app.js
const Koa = require('koa')
const mongoose = require('mongoose')
const cors = require('koa2-cors')
const router = require('koa-router')()
// import router from './routes'Const app = new Koa() // Use (cors({exposeHeaders: ['WWW-Authenticate'.'Server-Authorization'.'Date'],
maxAge: 100,
credentials: true,
allowMethods: ['GET'.'POST'.'OPTIONS'],
allowHeaders: ['Content-Type'.'Authorization'.'Accept'.'X-Custom-Header'.'anonymous']})); const db = mongoose.connect("mongodb://localhost/testDB")
var UserSchema = new mongoose.Schema({
username:String,
password:String,
email:String
});
var User = mongoose.model('User',UserSchema);
router.get('/', async (ctx, next) => {
let val = null
const data = await User.findOne({username: 'yidong'})
console.log('data', data)
const result = {
code:200,
response: data,
ts: 12345
}
ctx.response.body = result
return result
})
app.use(router.routes());
app.listen(9000);
console.log('app started at port 9000... ')
Copy the code
package.json
{
"name": "yid"."version": "1.0.0"."description": ""."main": "app.js"."dependencies": {
"babel-plugin-transform-es2015-modules-commonjs": "^ 6.26.2"."babel-register": "^ 6.26.0"."koa": "^ 2.5.3." "."koa-bodyparser": "^ 2"."koa-router": "^ 7.4.0"."koa2-cors": "^ 2.0.6"."mongoose": "^ 5.2.17"."nodemon": "^ 1.18.4"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."start": "nodemon app.js"
},
"author": ""."license": "ISC"
}
Copy the code
start.js
require('babel-register')
(
{
plugins: ['babel-plugin-transform-es2015-modules-commonjs'],
}
)
module.exports = require('./app.js')
Copy the code
routes/index.js
const router = require('koa-router')()
router.get('/', async (ctx, next) => {
ctx.body = "<div>Hello</div>"
})
router.get('/string', async (ctx, next) => {
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
ctx.body = {
title: 'koa2 json'
}
})
// module.exports = router
export default router
Copy the code
At this point we can happily start our NodeJS + KOA project, with a little file processing, module differentiation, and a basic framework can be completed.