亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vite?vue3下配置history模式路由的步驟記錄

 更新時(shí)間:2023年01月28日 12:00:58   作者:pakchoily  
路由存在兩者模式,一種是歷史模式history,一種是hash模式,下面這篇文章主要給大家介紹了關(guān)于vite?vue3下配置history模式路由的相關(guān)資料,需要的朋友可以參考下

dev 模式

利用vite 配置代理,可以解決前端瀏覽器限制跨域問(wèn)題(當(dāng)然后端要自己配置好)

export default defineConfig({
    // 配置在打包時(shí),保障所有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)境,默認(rèn)會(huì)讀取這個(gè)里面的內(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)境下,就可以使用代理來(lái)訪問(wèn)后端了

pro模式

打包時(shí),會(huì)自動(dòng)識(shí)別 .env.production

# .env.production 
VITE_BASE_API=http://localhost:8080
VITE_BASE_URL=/vaccinationInfo
VITE_BASE_ENV=pro

由于生產(chǎn)模式時(shí),代理配置時(shí)不生效的,所以VITE_BASE_API直接指向服務(wù)器地址

history模式 時(shí) 還要進(jìn)行以下配置

router\index.ts

history: createWebHistory(import.meta.env.VITE_BASE_URL as string),

用一個(gè)指定的url地址

nginx 配置

當(dāng)然,打包后放到nginx也需要配置

  location /vaccinationInfo {
        alias  /usr/share/nginx/html/vaccinationInfo;
        index  index.html index.htm;
        try_files $uri $uri/ /vaccinationInfo/index.html; # 解決頁(yè)面刷新404
    }	

然后在html中新建vaccinationInfo文件夾,把打包好的文件丟進(jìn)去就行

后端配置

寫(xiě)一個(gè)配置類(lèi)

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 允許跨域,以及自行配置
     *
     * @param registry 跨域注冊(cè)器
     */
    @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 跨域注冊(cè)器
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*") // SpringBoot2.4.0以上[allowedOriginPatterns]代替[allowedOrigins]
                .allowedMethods("*")
                .maxAge(3600)
                .allowedHeaders("*")
                .allowCredentials(true);
    }

    /**
     * 添加API攔截器,對(duì)所有數(shù)據(jù)API進(jìn)行攔截
     *
     * @param registry 攔截器注冊(cè)器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注冊(cè)攔截規(guī)則
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(jwtTokenInterceptor);
        // 攔截配置
        interceptorRegistration.addPathPatterns(interceptorPathBean.getInclude());
    }

}

重寫(xiě)addInterceptors 方法

配置JWT攔截器

@Component
public class JWTTokenInterceptor implements HandlerInterceptor {

    @Resource
    private JWTResult jwtResult;

    /**
     * 攔截對(duì)數(shù)據(jù)API的請(qǐng)求,判斷jwt令牌是否有效,沒(méi)有則返回401
     *
     * @param request  請(qǐng)求
     * @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 {

        //非簡(jiǎn)單請(qǐng)求會(huì)預(yù)先使用OPTIONS方法請(qǐng)求一次,這里直接返回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ā)揮
        //這才是真正的請(qǐng)求,需要驗(yàn)證jwt令牌
        //請(qǐng)求數(shù)據(jù)API時(shí)的目標(biāo)url
        String path = request.getRequestURI();
        String jwt = request.getHeader("Authorization");

        //對(duì)每次數(shù)據(jù)API請(qǐng)求進(jìn)行攔截,如果jwt令牌不合法,則返回401;通過(guò)則繼續(xù)放行,因此數(shù)據(jù)controller不需要再次判斷jwt令牌是否合法
        boolean verify = jwtResult.verify(jwt,path);
        //如果校驗(yàn)不通過(guò)
        if (!verify) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"msg\":\"jwt校驗(yàn)失敗\"}");
        }
        return verify;
    }

}

以上是重點(diǎn)處理 OPTIONS 預(yù)先請(qǐng)求,這個(gè)在非簡(jiǎn)單請(qǐng)求時(shí)會(huì)預(yù)先發(fā)出,典型場(chǎng)景就是打包后的前端工程,在請(qǐng)求后端是就會(huì)發(fā)出這個(gè)OPTIONS請(qǐng)求。

后面那些就是業(yè)務(wù)邏輯,自行發(fā)揮即可

補(bǔ)充幾個(gè)文件

InterceptorPathBean

@Data
@Component
@ConfigurationProperties(prefix = "interceptor-config.path") // 配置文件的前綴
public class InterceptorPathBean {
    /*
     * 需要攔截的路徑
     */
    private List<String> include;
}

application.yml

# 攔截器路徑攔截
interceptor-config:
  path:
    #該路徑下任何類(lèi)型請(qǐng)求均攔截
    include:
      - /telInfo/**
      - /vaccinationInfo/**

以上,就可以在vue中站著用history模式了

總結(jié)

到此這篇關(guān)于vite vue3下配置history模式路由的文章就介紹到這了,更多相關(guān)vite vue3配置history模式路由內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論