banner
Hi my new friend!

Node+express案例

Scroll down

|

登陆页面/html版本(静态资源)


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
51
52
53
54
55
56
57
58
59
60
const http = require('http')
const app = http.createServer()
const fs = require('fs')
const url = require('url')
const path = require('path')
const { json } = require('express')
let lodash = require('lodash')
app.on('request', (req, res) => {
req.url = req.url.toLowerCase()
let urlObj = url.parse(req.url, true)
if (req.url == '/' || req.url == 'index' || req.url == 'submit') {
fs.readFile(path.join(__dirname, 'view', 'submit.html'), 'utf8', (err, data) => {
if (err) throw err
res.end(data)
})
} else if (req.url == '/login') {
fs.readFile(path.join(__dirname, 'view', 'login.html'), 'utf8', (err, data) => {
if (err) throw err
res.end(data)
})
}
else if(req.url == "/home"){
fs.readFile(path.join(__dirname, 'view', 'home.html'), 'utf8', (err, data) => {
if (err) throw err
res.end(data)
})
}
else if (req.url.startsWith('/add') && req.method == 'GET') {
let content = urlObj.query
fs.readFile(path.join(__dirname, 'data', 'kaoshi.json'), 'utf8', (err, data) => {
if (err && err.code != 'ENOENT') throw err
let arr = JSON.parse(data || '[]')
arr.push(content)
fs.writeFile(path.join(__dirname,'data','kaoshi.json'),JSON.stringify(arr,null,' '),(err)=>{
if(err) throw err
res.writeHead(302, 'Found', {
'Location': 'login'
})
res.end()
})

})
} else if(req.url.startsWith('/out')&& req.method=='GET'){
let count = urlObj.query
fs.readFile(path.join(__dirname,'data','kaoshi.json'),'utf-8',(err,data)=>{
if(err) throw err
let arr = JSON.parse(data)
var m = lodash.findIndex(arr, count)
if(m>=0){
res.writeHead(302, 'Found', {
'Location': '/home'
})
res.end()
}
})

}
}).listen(3000, () => {
console.log("服务启动,请访问:http://localhost:3000")
})

express + cors跨域

1
2
3
var app = express();
var cors = require("cors") //cors同源跨域
app.use(cors)

header跨域

1
2
3
4
5
6
7
8
9
10
11
12
13
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('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Origin', '*')
// res.header('Access-Control-Allow-Headers', 'content-type,curUserId,token,platform');
// res.header('Access-Control-Allow-Headers', 'curUserId,token,platform');
res.header('X-Powered-By', '3.2.1');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
})

用户 注册 / 登陆 / 验证

注册

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
app.use(cors()) //设置cores同源跨域
app.post('/user/add', urlencodedParser, (req, res) => {
let content = req.body
fs.readFile(path.join(__dirname, 'data', 'Login.json'), 'utf-8', (err, data) => {
if (err) throw err
let str = JSON.parse(data)
var m = lodash.findIndex(str, content);//判断账户名密码是否正确
var n = lodash.findIndex(str, function (o) {//判断用户名是否存在
return o.userName === content.userName;
});
if (m >= 0 || n >= 0) {
res.send({ code: 201, message: "该用户已经存在" })
} else {
content.id = JSON.parse(data).length + 1
content.time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') //用户注册时间
const secret = 'yating';
content.token = jwt.sign(content, secret)//生成用户专属令牌token
var arr = JSON.parse(data || "[]")
arr.push(content)
fs.writeFile(path.join(__dirname, 'data', 'Login.json'), JSON.stringify(arr, null, " "), (err) => {
if (err) throw err
fs.readFile(path.join(__dirname, 'data', 'Login.json'), 'utf-8', (err, data) => {
res.send({ code: 200, message: "已添加该用户" })
})
})
}

})
})

登陆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.use(cors())
app.post("/login/add", urlencodedParser, (req, res) => {
let content = req.body
console.log(content);
fs.readFile(path.join(__dirname, 'data', 'Login.json'), 'utf-8', (err, data) => {
if (err) throw err
var arr = JSON.parse(data)
var m = lodash.findIndex(arr, content)
if (m >= 0) {
const token = jwtSign({_id:arr[m].id}) //返回带有时效的token
res.send({ code: 200, message: "登陆成功", token:token })
} else {
res.send({ code: 201, message: "登陆失败该用户不存在/密码错误" })
}
})
})

验证token jwt插件

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
//utils/jsw
const jwt = require('jsonwebtoken')

const jwtKey = 'junkaicool' // token生成的密匙

const jwtSign = (data) => { // token生成函数,有效时间为一个小时
const token = jwt.sign(data, jwtKey, {expiresIn:60*60})
return token
}

const jwtCheck = (req, res, next) => { // token验证函数
const token = req.headers.token
jwt.verify(token, jwtKey, (err, data) => {
if (err) {
res.send({
code: '99999999',
msg: 'token无效'
})
} else {
req.jwtInfo = data
next()
}
})
}

module.exports = {
jwtSign,
jwtCheck
}
1
2
3
4
5
6
7
8
9
10
//验证是否登陆
const {jwtCheck} = require('./utils/jsw')
// header传递token值判断是否登陆 和token值是否失效
app.get("/token",jwtCheck,(req,res)=>{
res.send({
code:200,
meg:"验证成功"
})
})

获取博客列表数据

1
2
3
4
5
6
7
8
9
10
11
//获取博客所有文章
app.get("/blog/list", (req, res) => {
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
if (err) throw err
res.send({
code:200,
message:"数据获取成功",
list:data
})
})
})

添加博客

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
//添加博客
app.post("/blog/add", urlencodedParser, (req, res) => {
let content = req.body//获取传递的数据
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
if (err) throw err
if(content.categoryId!=undefined){
content.id = JSON.parse(data).length + 1 //id
content.categoryId = Number(content.categoryId) //用户id
content.time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')//生成添加时间 moment插件
var arr = JSON.parse(data || "[]")
arr.push(content)
fs.writeFile(path.join(__dirname, 'data', 'list.json'), JSON.stringify(arr, null, " "), (err) => {
if (err) throw err
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
res.send(data)
})
})
}else{
res.send({
code:201,
message:"缺少必要参数"
})
}
})
})

获取单条博客数据

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

//获取单条博客文章详情
app.post("/blog/list/:id", (req, res) => {
var arg = url.parse(req.url).path
var ids = arg.match(/\d+/g).join(" ")
fs.readFile(path.join(__dirname, "data", "list.json"), 'utf-8', (err, data) => {
if (err) throw err
let str = JSON.parse(data)
var n = lodash.findIndex(str, function (o) { return o.id == ids; })
if (n >= 0) {
res.send(str[n])
} else {
res.send({ code: 201, message: "暂无此数据" })
}

})
})

删除博客

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//删除博客文章
app.delete("/blog/list/delete/:id", (req, res) => {
var arg = url.parse(req.url).path
var ids = arg.match(/\d+/g).join(" ")
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
if (err) throw err
let str = JSON.parse(data)
var s = lodash.remove(str, function (n) {
return n.id == ids;
});
fs.writeFile(path.join(__dirname, 'data', 'list.json'), JSON.stringify(str, null, " "), (err) => {
if (err) throw err
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
res.send(data)
})
})
})
})

博客更新

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
//更新博客
app.put("/blog/list/put/:id", (req, res) => {
let content = req.body
var arg = url.parse(req.url).path
var ids = arg.match(/\d+/g).join(" ")
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
if (err) throw err
let str = JSON.parse(data)
var n = lodash.findIndex(str, function (o) { return o.id == ids; })
if (n >= 0) {
content.time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
content.id = str[n].id
str[n] = content
fs.writeFile(path.join(__dirname, 'data', 'list.json'), JSON.stringify(str, null, " "), (err) => {
if (err) throw err
fs.readFile(path.join(__dirname, 'data', 'list.json'), 'utf-8', (err, data) => {
res.send(data)
})
})
} else {
res.send({ code: 201, message: "暂无数据" })
}

})
})