定制小程序开发vite vue3 下配置 history 模式路由

dev 模式

  • 利用 配置代理,定制小程序开发可以解决前端浏览器限定制小程序开发制跨域问题(定制小程序开发当然后端要自己配置好)

    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,    }})
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    配置.env

    在dev 环境,默认会读取这个里面的内容

    # .env.developmentVITE_BASE_API=/apiVITE_BASE_URL=/vaccinationInfoVITE_BASE_ENV=dev
    • 1
    • 2
    • 3
    • 4
    • 5

    配置axios

    import axios from "axios";const service = axios.create({    baseURL: import.meta.env.VITE_BASE_API as string,    timeout: 3600})
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这样在dev环境下,就可以使用代理来访问后端了

pro模式

打包时,会自动识别 .env.production

# .env.production VITE_BASE_API=http://localhost:8080VITE_BASE_URL=/vaccinationInfoVITE_BASE_ENV=pro
  • 1
  • 2
  • 3
  • 4

由于生产模式时,代理配置时不生效的,所以VITE_BASE_API直接指向服务器地址

history模式 时 还要进行以下配置

router\index.ts

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

用一个指定的url地址

nginx 配置

当然,打包后放到nginx也需要配置

  location /vaccinationInfo {        alias  /usr/share/nginx/html/vaccinationInfo;        index  index.html index.htm;        try_files $uri $uri/ /vaccinationInfo/index.html; # 解决页面刷新404    }	
  • 1
  • 2
  • 3
  • 4
  • 5

然后在html中新建vaccinationInfo文件夹,把打包好的文件丢进去就行

后端配置

写一个配置类

@Configurationpublic 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);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

如果需要配置拦截JWT,可以采取以下操作

@Configurationpublic 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拦截器,对所有数据API进行拦截     *     * @param registry 拦截器注册器     */    @Override    public void addInterceptors(InterceptorRegistry registry) {        // 注册拦截规则        InterceptorRegistration interceptorRegistration = registry.addInterceptor(jwtTokenInterceptor);        // 拦截配置        interceptorRegistration.addPathPatterns(interceptorPathBean.getInclude());    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46

重写addInterceptors 方法

配置JWT拦截器

@Componentpublic class JWTTokenInterceptor implements HandlerInterceptor {    @Resource    private JWTResult jwtResult;    /**     * 拦截对数据API的请求,判断jwt令牌是否有效,没有则返回401     *     * @param request  请求     * @param response 响应     * @param handler  处理器     * @return 是否继续执行,true继续执行,false不继续执行     * @throws Exception 异常     */    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        //非简单请求会预先使用OPTIONS方法请求一次,这里直接返回true        if (request.getMethod().equals("OPTIONS")) {            response.setStatus(200);            //在拦截器中设置允许跨域            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;        }        //业务逻辑,自行发挥        //这才是真正的请求,需要验证jwt令牌        //请求数据API时的目标url        String path = request.getRequestURI();        String jwt = request.getHeader("Authorization");        //对每次数据API请求进行拦截,如果jwt令牌不合法,则返回401;通过则继续放行,因此数据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;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

以上是重点处理 OPTIONS 预先请求,这个在非简单请求时会预先发出,典型场景就是打包后的前端工程,在请求后端是就会发出这个OPTIONS请求。

后面那些就是业务逻辑,自行发挥即可

补充几个文件

InterceptorPathBean

@Data@Component@ConfigurationProperties(prefix = "interceptor-config.path") // 配置文件的前缀public class InterceptorPathBean {    /*     * 需要拦截的路径     */    private List<String> include;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

application.yml

# 拦截器路径拦截interceptor-config:  path:    #该路径下任何类型请求均拦截    include:      - /telInfo/**      - /vaccinationInfo/**
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发