express

作者 新城 日期 2018-06-06
express

官网

vue-cli脚手架集成express

1.安装vue-cli脚手架不再称述
2.找到webpack.dev.conf.js

引入资源

1
2
3
4
5
6
7
8
9
10
11
//引入express
const express = require('express');

//赋值-app
const app = express();

// 引入axios 用于转发请求
const axios = require('axios');

// 引入json解析中间件 用于接收post请求
const bodyParser = require('body-parser');

配置express

3.添加服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
devWebpackConfig中配置 before
devServer:{
before(app){
//服务器端设置 是否允许接收来自任何域名下的请求
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next()
}),
//Get请求
//Post请求
//接收文件
},
...
}

接收get请求

1
2
3
4
5
6
7
app.get('/api/getUserInfo',function(req,res){
// get请求的数据
req.params

// res 返回的数据
res.json()
})

接收post请求

使用post请求接收参数的时候

需要添加post请求json解析中间件

1
2
3
4
5
6
7
app.use(bodyParser.json())  // 措不及防的一个 bug
app.use(bodyParser.urlencoded({extended: true}))

app.post('/api/setUserInfo',function(req,res){
// post请求的数据
req.body
})

接收文件并转发

使用axiox拦截器的时候 上传文件可能失效
取消拦截器的使用
代理服务器可以直接从客户端获取cookie 从而判断客户端是否处于登陆状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// npm install multer

const multer = require('multer')
const upload = multer()

// 文件上传格式预览
app.post('/api/upLoadFile',upload.single('file'),function(req,res){
var url = requireUrl + '/import/expense/'+req.body.id+'/preview?token='+req.cookies.token
var config = {
headers: {'Content-Type': 'multipart/form-data; charset=utf-8; boundary="another cool boundary";'}
}

axios.post(url,req.file,config).then((response)=>{
res.json(response.data)
}).catch((e)=>{
console.log(e)
res.json({error:{message:'文件上传失败',code:500}})
})
})

结合axios发送http请求

node端使用axios发送http请求

1
2
3
4
5
6
7
8
9
app.get('/api/...',function(req,res){
var url = 'http://www.baidu.com'
axios.get(url,{params:{req.query}}).then((response)=>{
res.json(response.data)
}).catch((e)=>{
//这里可以自己定义返回的错误类型数据
console.log(e)
})
})

使用buffer编码 将文件读写进内存中 然后直接返回用户
当用户流量大的时候 IO流 操作比较慢 影响用户访问数量

记住url 该方法暂用内存 文件大小不能过大 利用牺牲内存的方法 去换取用户访问速度流量