vite?vue3下配置history模式路由的步驟記錄
dev 模式
利用vite 配置代理,可以解決前端瀏覽器限制跨域問題(當然后端要自己配置好)
export default defineConfig({
// 配置在打包時,保障所有css\js能被找到
base: './',
//自帶配置
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
// 配置/api代理
server: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
},
//打包前先清空原有打包文件
build: {
emptyOutDir: true,
}
})
配置.env
在dev 環(huán)境,默認會讀取這個里面的內(nèi)容
# .env.development VITE_BASE_API=/api VITE_BASE_URL=/vaccinationInfo VITE_BASE_ENV=dev
配置axios
import axios from "axios";
const service = axios.create({
baseURL: import.meta.env.VITE_BASE_API as string,
timeout: 3600
})
這樣在dev環(huán)境下,就可以使用代理來訪問后端了
pro模式
打包時,會自動識別 .env.production
# .env.production VITE_BASE_API=http://localhost:8080 VITE_BASE_URL=/vaccinationInfo VITE_BASE_ENV=pro
由于生產(chǎn)模式時,代理配置時不生效的,所以VITE_BASE_API直接指向服務(wù)器地址
history模式 時 還要進行以下配置
router\index.ts
history: createWebHistory(import.meta.env.VITE_BASE_URL as string),
用一個指定的url地址
nginx 配置
當然,打包后放到nginx也需要配置
location /vaccinationInfo {
alias /usr/share/nginx/html/vaccinationInfo;
index index.html index.htm;
try_files $uri $uri/ /vaccinationInfo/index.html; # 解決頁面刷新404
}
然后在html中新建vaccinationInfo文件夾,把打包好的文件丟進去就行
后端配置
寫一個配置類
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 允許跨域,以及自行配置
*
* @param registry 跨域注冊器
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // SpringBoot2.4.0以上[allowedOriginPatterns]代替[allowedOrigins]
.allowedMethods("*")
.maxAge(3600)
.allowedHeaders("*")
.allowCredentials(true);
}
}
如果需要配置攔截器攔截JWT,可以采取以下操作
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private JWTTokenInterceptor jwtTokenInterceptor;
private InterceptorPathBean interceptorPathBean;
@Autowired
public void setJwtTokenInterceptor(JWTTokenInterceptor jwtTokenInterceptor) {
this.jwtTokenInterceptor = jwtTokenInterceptor;
}
@Autowired
public void setInterceptorPathBean(InterceptorPathBean interceptorPathBean) {
this.interceptorPathBean = interceptorPathBean;
}
/**
* 允許跨域,以及自行配置
*
* @param registry 跨域注冊器
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // SpringBoot2.4.0以上[allowedOriginPatterns]代替[allowedOrigins]
.allowedMethods("*")
.maxAge(3600)
.allowedHeaders("*")
.allowCredentials(true);
}
/**
* 添加API攔截器,對所有數(shù)據(jù)API進行攔截
*
* @param registry 攔截器注冊器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注冊攔截規(guī)則
InterceptorRegistration interceptorRegistration = registry.addInterceptor(jwtTokenInterceptor);
// 攔截配置
interceptorRegistration.addPathPatterns(interceptorPathBean.getInclude());
}
}
重寫addInterceptors 方法
配置JWT攔截器
@Component
public class JWTTokenInterceptor implements HandlerInterceptor {
@Resource
private JWTResult jwtResult;
/**
* 攔截對數(shù)據(jù)API的請求,判斷jwt令牌是否有效,沒有則返回401
*
* @param request 請求
* @param response 響應(yīng)
* @param handler 處理器
* @return 是否繼續(xù)執(zhí)行,true繼續(xù)執(zhí)行,false不繼續(xù)執(zhí)行
* @throws Exception 異常
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//非簡單請求會預(yù)先使用OPTIONS方法請求一次,這里直接返回true
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(200);
//在攔截器中設(shè)置允許跨域
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "3600");
return true;
}
//業(yè)務(wù)邏輯,自行發(fā)揮
//這才是真正的請求,需要驗證jwt令牌
//請求數(shù)據(jù)API時的目標url
String path = request.getRequestURI();
String jwt = request.getHeader("Authorization");
//對每次數(shù)據(jù)API請求進行攔截,如果jwt令牌不合法,則返回401;通過則繼續(xù)放行,因此數(shù)據(jù)controller不需要再次判斷jwt令牌是否合法
boolean verify = jwtResult.verify(jwt,path);
//如果校驗不通過
if (!verify) {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("{\"code\":401,\"msg\":\"jwt校驗失敗\"}");
}
return verify;
}
}
以上是重點處理 OPTIONS 預(yù)先請求,這個在非簡單請求時會預(yù)先發(fā)出,典型場景就是打包后的前端工程,在請求后端是就會發(fā)出這個OPTIONS請求。
后面那些就是業(yè)務(wù)邏輯,自行發(fā)揮即可
補充幾個文件
InterceptorPathBean
@Data
@Component
@ConfigurationProperties(prefix = "interceptor-config.path") // 配置文件的前綴
public class InterceptorPathBean {
/*
* 需要攔截的路徑
*/
private List<String> include;
}
application.yml
# 攔截器路徑攔截
interceptor-config:
path:
#該路徑下任何類型請求均攔截
include:
- /telInfo/**
- /vaccinationInfo/**
以上,就可以在vue中站著用history模式了
總結(jié)
到此這篇關(guān)于vite vue3下配置history模式路由的文章就介紹到這了,更多相關(guān)vite vue3配置history模式路由內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-awesome-swiper 基于vue實現(xiàn)h5滑動翻頁效果【推薦】
說到h5的翻頁,很定第一時間想到的是swiper。但是我當時想到的卻是,vue里邊怎么用swiper。這篇文章主要介紹了vue-awesome-swiper - 基于vue實現(xiàn)h5滑動翻頁效果 ,需要的朋友可以參考下2018-11-11
nuxt.js服務(wù)端渲染中axios和proxy代理的配置操作
這篇文章主要介紹了nuxt.js服務(wù)端渲染中axios和proxy代理的配置操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Elementui如何限制el-input框輸入小數(shù)點
這篇文章主要介紹了Elementui如何限制el-input框輸入小數(shù)點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
淺談vue中computed屬性對data屬性賦值為undefined的原因
本文主要介紹了淺談vue中computed屬性對data屬性賦值為undefined的原因,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
vue.js實現(xiàn)帶日期星期的數(shù)字時鐘功能示例
這篇文章主要介紹了vue.js實現(xiàn)帶日期星期的數(shù)字時鐘功能,涉及vue.js基于定時器的日期時間運算與數(shù)值操作相關(guān)使用技巧,需要的朋友可以參考下2018-08-08

