I. Development Interface Specification (Restful API)
1, a clear demand
Role: to ensure everyone's written specifications as
an example:
Back-end resources posted to the URL -> URL to access resources through the front -> and indicates the operation to a resource via HTTP verbs
backend defined interfaces -> Front Request Interface -> HTTP verbs purpose operating table (get get new post put updates, etc.)
- For Li
List: Access - / module name (get)
details page: visit - / module name / number (get)
add Page: Access - / module name / create (get)
treatment: Access - / module name (post)
modified page: access - / module name / number / edit (get)
treatment: access - / module name / number (put)
delete: access - / module name / number (delete)
HTTP verb: get, post, put, delete
Second, the initialization (Express scaffolding frame)
Scaffolding: It is a noun, not explain
Role: the scaffolding can be generated by the project code
1, the frame generating codes express express
Step 1: mounting frame generator ( NPM the install Express-Generator -g )
Step 2: express command generated by the newly installed shop
project ( express project name )
Step 3: mounting frame dependent module
- cd shop
- npm install
Step 4: Start & Access test (foot care: command npm start)
So far express frame was set for. The following database connection and modularity
1, connected to a database (Modular)
- Step 1: & global function package global profile
Create a file common / config.json
{
"db_config":{
"host" : "localhost",
"port" : 27017, // 数据库的端口号
"dbname" : "sixbuyshop" // 数据库的名字
}
}
Create a file common / db.js
Pay attention: Copy the code below before the first [npm i mongoose]
// 导入模块
const mongoose = require('mongoose');
// 导入配置文件
const configObj = require(process.cwd() + "/common/config.json").db_config
// 连接数据库
const db = mongoose.createConnection(`mongodb://${configObj.host}:${configObj.port}/${configObj.dbname}`, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
if(err){
console.log('---------------------------------------')
console.log('数据库连接失败:', configObj)
console.log('---------------------------------------')
return;
}
console.log('数据库连接成功');
})
// 声明全局变量 全局都可以用
global.db = db
Create a file common / utils.js
// http协议状态码(背 明晚抽查 说不出来30遍)
// 2XX 成功
// 200-成功 正常返回 (服务器已成功处理了请求)
// 201-创建 成功创建数据 (表示服务器执行成功,并且创建了新的资源)
// 202-已接受 (服务器接受请求,但未处理)
// 3XX 重定向(服务器返回信息告知浏览器如何做后续操作才能成功处理请求)
// 301-永久(新网站)
// 302-临时(站内跳转)
// 304-浏览器缓存(请求成功检测为修改数据来源于浏览器)
// 4XX 客户端错误(客户端原因,妨碍了服务器的处理)
// 400-前端请求失败,方式参数不对
// 401-未通过 HTTP 认证的认证信息(场景:网页登录失败)
// 403-禁止访问(码云私有仓库)
// 404-文件不存在
// 405-请求方法有误
// 5XX 服务端错误
// 500-服务器端在执行请求时发生了错误
// 503-服务器过载,无法处理请求
// -------------------------------
/**
* 接口响应
* @param {Object} res 响应对象
* @param {Number} code 状态码
* @param {String} message 提示信息
* @param {mixed} data 响应数据
*/
global.sendJson = (res, code, message, data = null) => {
res.json({
"meta" : {
"state" : code,
"msg" : message
},
"data" : data
});
}
Inlet configuration files into the database
require(process.cwd() + “/common/db.js”)
require(process.cwd() + “/common/utils.js”)
Second, routing
1, steps to establish a route
Established home under the Home directory routing module routes
var express = require('express');
var router = express.Router();
// 以前直接在 这里写逻辑
// 但不知道有几个路由
// 解决 :去controller目录中定义 这里调用
// process.cwd() 表示命令执行的文件路径
//const { getHomeBannerList } = require(process.cwd() + '/controller/home')
// 首页轮播
// router.get('/', getHomeBannerList )
/* GET users listing. */
router.get ('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
app.js file import route activation
Using mvc thought to separate logic code
Model Model - responsible for data processing,
View View - responsible for displaying the page
Controller Controller - which M and which is responsible for scheduling the use of V
Method for establishing controller / home.js responsible for calling the next model
// const { usersGetList } = require(process.cwd() + "/model/home")
//用户列表
const getHomeBannerList = async (req, res, next) =>{
// const userData =await usersGetList()
sendJson(res, 200, "操作成功")
// console.log(req.body)
// const insertObj = req.body
// const cbData=await usersModelPost(insertObj);
// if(cbData){
// sendJson(res, 200, "操作成功",cbData)
// }else{
// sendJson(res, 500, "操作失败",cbData);
// }
}
module.exports={
getHomeBannerList
}
The establishment of model / home.js write some logic code request database
const model = db.model('user',{
name:{type:String},
pwd:{type:String},
sex:{type:String, default:"女"}
})
// 用户列表的查
const usersGetList = ()=>{
return model.find()
.then(res=>{
return res
})
.catch(err=>{
console.log('用户名查错误:'+ err)
return null
})
}
module.exports={
usersGetList
}