项目打包
npm run build(生成一个文件夹,里面是原始的font,img,css,js等文件,并包含一个纯粹的index.html,该html文件不是点击直接运行的 而是需要部署在服务器上的)
完整的请求地址必然是:完整的协议名+主机名+端口号+路由名
3种服务器部署
(1) 本地服务器部署
后端有个serve.js文件。
a. 引入express:const express = require(‘express’)
b. 配置端口号:const port = 8088
c. 创建一个app服务实例: const app = express()
d. 配置静态资源:app.use(express.static(__dirname+’/public’))
e. 绑定端口监听: app.listen(port,()=>{})
自动打开端口的瞬间,加载了整个网页,网页引入了js,靠js、完成了前端路由跳转,当刷新的时候,它误以为该路由是后端路由,他回去后端请求该路由页面。解决方案:
a. hash路由方式:找到前端项目,路由配置中,mode由history换成hash模式(描点是不触发服务器的)
b. 无法匹配后端路由时,返回index.html,index.html中的js奏效在serve.js文件中增加app.get(‘*’,(req,res)=>{
res.sendFile(__dirname + ‘public/index.html’)
})
c. connect-history-api-fallback:专门处理前端路由的.通过该中间件完成配置
a) 安装 npm install --save connect-history-api-fallback
b) 引用:var history = require(‘connect-history-api-fallback’)
c) 使用中间件 var connect = require(‘connect’)
var app = connect()
.use(history())
.listen(3000)
//配置静态资源 app.use(express.static(__dirname+’/public’))
使用connect-history-api-fallback可以让配置更灵活,比如/login临时不需要作为前端路由处理,则可以按照一下方式配置
app.use(history({
verbose:false,
rewrite:[
{from :/^\/login.*$/,to:(context)=>context.parseUrl.path}
]
})
浏览器地址栏里发出的请求都是get请求
使用http-proxy-middleware代理后端。
a. 安装:npm i http-prxoy-middleware
b. 使用:app.use(
‘/dev’,
createProxyMiddleware({
target:’sph-h5-api.atguigu.cn’ //代理地址
changeOrigin:true,
pathRewrite:{‘^/dev’:’’} //
})
)
打包完过后,就是纯js文件,没有脚手架啦,没有代理服务器了,
(2) nginx服务器部署
① nginx简介,主要功能
1) 反向代理
2) 负载均衡
3) 静态内容服务
4) HTTP/2支持
5) SSL/TLS支持
6) 高速缓存
② nginx配置代理练习
配置,在nginx.cong 配置文件中的location的root上路径改为打包好的index.html的路径(注意,为防止c盘的权限问题,一般将index文件放置d盘等非c盘中。)
然后重启nginx,在进程中关闭nginx任务,重新启动nginx.exe.index页面虽有有,但是又会重复上面的两个问题
(1)路由问题
解决方案:配置nginx根目录在location / 配置中,增加try_files uri//index.html //解决刷新抱404问题
(2)接口路径代理问题
解决方案:配置代理。 location /dev/ {
proxy_pass sph-h5-api.atguigu.cn/ //设置代理目标
}
③ nginx部署前端项目
(3) 云服务器部署
xshell :连接远程服务器敲命令
xftp:连上远程linux服务器,传文件
在xshell中,安装nginx,yum install nginx.
然后在nginx.config更改配置
配置后路径带有的是ip,在阿里云产品中购买域名,让域名和ip对应上