1.初始化项目npm init -y
2.使用Express框架创建服务器,用mongoose连接数据库,cors解决跨域npm i express mongoose cors
3.1 index.js文件,启动node服务
const express = require('express')
const cors = require('cors')
const app = express()
//解决跨域
app.use(cors())
//express内置了post参数解析
app.use(express.urlencoded({ extended: false }))
const apiRouter = require('./router')
app.use(apiRouter)
app.listen(3008, function () {
console.log('app is runing at port 3008');
})
3.2 db.js 连接mongoDB
const mongoose = require('mongoose')
const IP = 'localhost'
const PORT = 27017
const DB_NAME = 'org'
//连接
mongoose.connect(`mongodb://${IP}:${PORT}/${DB_NAME}`, {
useNewUrlParser: true
})
//连接成功
mongoose.connection.on('connected', () => {
console.log('Mongoose connection success')
})
//连接异常
mongoose.connection.on('error', (err) => {
console.log('Mongoose connection error:' + err)
})
//连接成功
mongoose.connection.on('disconnected', () => {
console.log('Mongoose connection disconnected')
})
module.exports = mongoose
3.3 router.js 定义接口以及方法
const express = require('express')
const router = express.Router()
const dataList = require('../serve_schema/dataList')
let result = {
code: 200,
msg: 'ok'
}
//创建数据
router.post('/postData', async (req, res) => {
let postData = new dataList({ ...req.body })
await postData.save(err => {
if (err) {
throw err
} else {
res.json({ ...result })
}
})
})
//获取数据
router.get('/getList', async (req, res) => {
let { start, limit } = req.query
if (start == undefined) {
start = 0;
}
if (limit == undefined) {
limit = 10;
}
let data = await dataList.find().skip(Number(start)).limit(Number(limit));
res.json({ ...result, data })
})
module.exports = router
3.4 serve_scheam文件夹下的dataList.js,创建数据库模型,也就是创建一个数据库的表,用来存数据,设置数据的一些字段等。
const mongoose = require('../serve_setting/db')
const { Schema } = mongoose
const userSchema = new Schema({
username: { type: String },
password: { type: String },
email: { type: String },
mobile: { type: String },
status: { type: Number, default: 1 },
}, { versionKey: false })
// versionKey 不显示版本字段
module.exports = mongoose.model('User', userSchema, 'user')
//第三个参数,指定集合名,不自动匹配对应的复数形式users。
4.全局安装一个自动重启的node工具nodemonnpm install -g nodemon
5.配置启动文件,pageage.json
"scripts": {
"start": "nodemon http_serve/serve_setting/index.js"
},
至此,我们的后台接口就定义完成了。