Express基础教程

本文主要介绍Express基础教程

1创建并生成Express项目

代码如下:

1
2
3
4
5

mkdir myapp
cd myapp
npm init
npm install express --save

2安装mysql并初始化

安装mysql并设置账户请Google

执行如下sql创建数据库:

1
2
3
4
5
6
7
8
9
10
11
12

-- 创建新的 mydb 数据库
CREATE DATABASE mydb DEFAULT CHARSET UTF8MB4;
-- 使用 mydb 数据库
USE mydb;
-- 创建表
CREATE TABLE `user` (
`id` int(10) NOT NULL AUTO_INCREMENT, //id
`name` varchar(255) NOT NULL, //名称
`contact_information` varchar(255) NOT NULL, //邮箱或者手机号
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

3创建mysql连接池

进入项目根目录

执行如下代码:

1
2
3
4
5

mkdir config
cd config
touch index.js
touch db.js

index.js代码如下:

1
2
3
4
5
6
7
8
9

sql: {
host: 'localhost', // mysql访问地址
user: 'root', // mysql用户名
password: '123456', // mysql密码
database: 'mydb' // mysql数据库名
}

module.exports = sql

注:如果区分不通环境可增加多个环境的配置

db.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

var mysql = require('mysql')
var config = require('./index')
var pool = mysql.createPool(config.sql);
let query=(sql,callback)=>{
pool.getConnection(function(err,connection){
console.log(err)
connection.query(sql, function (err, rows, fields) {
callback(err,rows,fields)
connection.release()
})
})
}

exports.query = query

4编写mysq操作方法

以用户表增删改查为例

进入项目根目录

执行如下代码:

1
2
3

mkdir services
touch user.js

user.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

const db = require('../config/db')
let getUserList = () => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM USER', (err, rows) => {
if(err) {
reject(err);
}
resolve(rows);
})
})
}//显示全部 (select*)

let getUserItem = (attributename, attribute) => {
return new Promise((resolve, reject) => {
db.query(`SELECT * FROM USER WHERE ${attributename} = '${attribute}'`, (err, rows) => {
if(err) {
reject(err);
}
resolve(rows);
})
})
}//查询一行(传参)

let updateUser = (updateattributename, newdata,attributename,attribute) => {
return new Promise((resolve, reject) => {
db.query(`UPDATE USER SET ${updateattributename} = '${newdata}' WHERE ${attributename} = '${attribute}'`,(err,rows) => {
if(err) {
reject(err);
}
resolve(rows);
})
})
}//修改

let insertUser = (attributenames, attributes) => {
return new Promise((resolve, reject) => {
db.query(`INSERT INTO USER ${attributenames} VALUES ${attributes}`, (err,rows) => {
if(err) {
reject(err);
}
resolve(rows);
})
})
}//增加

exports.getUserList = getUserList
exports.getUserItem = getUserItem
exports.updateUser = updateUser
exports.insertUser = insertUser

5设置跨域访问并解析requestBody参数

进入项目根目录下

安装body-parser

在app.js中添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

var bodyParser = require("body-parser"); 添加于头部

... //其他代码

var app = express(); //改行为Express自带,无需自己写

app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
if(req.method=="OPTIONS"){
res.send({
code:0,
msg:"ok"
});/*让options请求快速返回*/
}else{
next();
}
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

6编写手机号和邮箱验证规则

进入项目根目录

执行如下代码:

1
2
3
4

mkdir utils
cd routes
touch validate.js

touch.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

/**
* @param {string} email
* @returns {Boolean}
*/
let validEmail = (email) => {
const reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
return reg.test(email)
}

/**
* @param {string} mobile
* @returns {Boolean}
*/
let validateMobile = (mobile) => {
const reg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
return reg.test(mobile)
}

7编写接口

进入项目根目录

执行如下代码:

1
2
3

cd routes
touch users.js

user.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

var express = require('express');
var router = express.Router();

router.post('/user', async function(req, res, next) {
const resBody={
code:999,
msg:"你的网络好像开了小差"
}
try {
const name = req.body.name
const contact_information = req.body.contact_information
if(!await require('../utils/validate').validateMobile(contact_information)&&!await require('../utils/validate').validEmail(contact_information)){
resBody.code=201
resBody.msg="手机号或邮箱格式不正确"
res.send(resBody)
}else if(!name){
resBody.code=201
resBody.msg="姓名不能为空"
res.send(resBody)
}else if((await require('../services/User').getUserItem('contact_information',contact_information)).length!=0){
resBody.code=201
resBody.msg="该手机号或邮箱已注册"
res.send(resBody)
}else{
let result = await require('../services/user').insertUser("(name,contact_information)",`('${name}','${name,contact_information}')`);
if(result){
resBody.code=0
resBody.msg="提交成功"
res.send(resBody)
}
}
} catch (e) {
console.log(e)
res.send(resBody)
}
});

module.exports = router;
扫一扫,请老师喝水