一个简易node服务(大佬请忽略),路由配置、get/post请求、本地模拟数据库
项目结构:
npm install koa koa-body koa-cors koa-router -S
npm install nodemon -D (若需要热更新,则安装nodemon并使用nodemon启动服务)
package.json
{
"name": "koa-node",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.11.0",
"koa-body": "^4.1.1",
"koa-cors": "0.0.16",
"koa-router": "^7.4.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
server.js
const Koa = require('koa')
const koaBody = require('koa-body')
const cors = require('koa-cors')
const httpPort = require('./config.js')
const server = new Koa()
let router = require('./router/index.js')
server.use(cors())
server.use((ctx, next) => {
return next()
})
server.use(koaBody())
server.use(router.routes())
server.listen(httpPort.httpPort, () => {
console.log('server is running localhost:' + httpPort.httpPort)
})
config.js
router/index.js
const router = new require('koa-router')()
let routes = require('./routes/index.js')
routes.forEach(r => {
router.all(r.path, r.handle)
})
module.exports = router
router/routes/index.js
let getData = require('./getData.js')
let addData = require('./addData.js')
module.exports = [
getData,
addData
]
router/routes/addData.js (模拟 POST 接口)
发送 POST 请求:localhost:3000/add-message
即可成功请求 ‘/add-message’
// POST 请求 body里取参数
let database = require( '../../database/index.js')
async function handle(ctx, next) {
let params = ctx.request.body
if (params) {
params.dateTime = new Date().toLocaleString()
ctx.body = { data: params, status: 200, message: '成功' }
database.addMessage(params)
} else {
ctx.body = { data: {}, status: 500, message: '参数错误' }
}
}
module.exports = {
path: '/add-message',
handle
}
router/routes/getData.js (模拟 GET 请求)
发送 GET 请求:localhost:3000/get-message
即可成功请求 ‘/get-message’
// GET 请求 query 里取参数
let database = require('../../database/index.js')
async function handle(ctx, next) {
let query = ctx.request.query
let messageData = database.getMessage()
ctx.body = { data: { messageData }, status: 200, message: '成功' }
}
module.exports = {
path: '/get-message',
handle
}
database/index.js (本地模拟数据库新增、获取数据)
let messageData = []
function addMessage(msg) {
messageData.unshift(msg)
}
function getMessage() {
return messageData
}
module.exports = { addMessage, getMessage }
README.md
# 一个Koa框架搭建的基本node服务
npm install
### 启动服务
npm start
或
node server.js
### 热更新启动
nodemon server.js