部署的基本问题
问题一:刷新404
原因:使用history模式是前端路由的模式,在子路由中手动刷新时,首先会触发后端路由,但是项目的路由都是前端路由,所以会get404
解决方法:
- 不使用history模式,而使用hash模式,这样不会因为路径触发后端路由
- 可以手写或使用中间件来将无法找到的后端路由重映射到首页路由
问题二:axios无法使用
原因:开发环境配置了代理服务器,通过代理服务器转发解决了跨域问题。
解决方法
- 通过对后端服务器设置代理,进行服务的转发
本地express服务端部署
通过本地开启express服务,通过静态服务来存放打包后的前端项目。
问题一的解决办法:通过将未匹配到的后端路由接收并重定向到首页通过前端路由处理,或者使用connect-history-api-fallback来处理。
const express = require('express');
const app = express();
const history = require('connect-history-api-fallback');
const port = 3000;
app.use(history());
app.use(express.static('public'));
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
问题二的解决办法:通过http-proxy-middleware来进行代理服务器的设置。
const proxy = require('http-proxy-middleware');
app.use('/api', proxy.createProxyMiddleware({ target: '需要重定向的地址', changeOrigin: true, pathRewrite: {'^/api' : ''} }));
本地nginx部署
问题一的解决办法
server {
listen 80;
server_name localhost;
location / {
root d:/server;
index index.html index.htm;
# 设置找不到的页面转到首页index.html
try_files $uri $uri/ /index.html;
}
}
问题二的解决办法
location /api/ {
# 重定向的地址
proxy_pass xxxx/;
}
云端服务器部署
在云端服务器上安装nginx并通过xshell连接远端启动服务,通过xftp来进行文件的上传和修改,其他和本地nginx操作一样。