一、环境:
① 服务器 Nginx1.21 ,宝塔部署;
② 前端 Vue3,后端 ThinkPHP6.1
二、情况:
① Vue3 和 TP6 前后端分离 及 前后端不一样的域名时 实现跨域请求问题 ;
② Vue3前端使用路由约束后,线上部署访问 404问题
三、方案:
1、跨域解决:
因为我的前端配置做了代理转发 ,下图:
所以 服务器中宝塔的配置,这样才能正常代理成功,下图:
# 配置与后端服务器地址的映射
location ^~ /webapi/ {
proxy_pass https://192.168.31.119:8089/webapi/;
}
后端中还得在请求接口的请求头设置 :
header('Access-Control-Allow-Origin:*');
//允许的请求头信息
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
//允许的请求类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
//允许携带证书式访问(携带cookie)
header('Access-Control-Allow-Credentials:true');
2、访问404
因为vue前端使用了路由策略,重写路由访问地址,如下代码:
import { createRouter, createWebHistory } from "vue-router";
import { defineAsyncComponent } from 'vue'; //异步组挂载器
const routes = [
{
path: "/",
name: "home",
component:() => import('../pages/home/index.vue'),
},
{
path: "/project/apply",
name: "projectApply",
component:() => import('../pages/project/apply.vue'),
},
]
export const router = createRouter({
history: createWebHistory(),
routes: routes
})
如果直接部署在线上服务器就会报404错误。
所以 在服务器中配置了:
location / {
try_files $uri $uri/ /index.html;
}
上面是把VUE前端部署到服务器后遇到的问题,因为遇到(部署)了两次了!所以这次记录下,下次部署有参考!
希望也能帮到大家!