-
利用vite 配置代理,可以解决前端浏览器限制跨域问题(当然后端要自己配置好)
export default defineConfig({ // 配置在打包时,保障所有cssjs能被找到 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 环境,默认会读取这个里面的内容
# .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环境下,就可以使用代理来访问后端了
打包时,会自动识别 .env.production
# .env.production VITE_BASE_API=http://localhost:8080 VITE_BASE_URL=/vaccinationInfo VITE_BASE_ENV=pro
由于生产模式时,代理配置时不生效的,所以VITE_BASE_API直接指向服务器地址
history模式 时 还要进行以下配置
routerindex.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 {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截规则
InterceptorRegistration interceptorRegistration = registry.addInterceptor(jwtTokenInterceptor);
// 拦截配置
interceptorRegistration.addPathPatterns(interceptorPathBean.getInclude());
}
}
重写addInterceptors 方法
配置JWT拦截器
@Component
public class JWTTokenInterceptor implements HandlerInterceptor {
@Resource
private JWTResult jwtResult;
@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;
}
}
以上是重点处理 OPTIONS 预先请求,这个在非简单请求时会预先发出,典型场景就是打包后的前端工程,在请求后端是就会发出这个OPTIONS请求。
后面那些就是业务逻辑,自行发挥即可
补充几个文件
InterceptorPathBean
@Data
@Component
@ConfigurationProperties(prefix = "interceptor-config.path") // 配置文件的前缀
public class InterceptorPathBean {
private List include;
}
application.yml
# 拦截器路径拦截
interceptor-config:
path:
#该路径下任何类型请求均拦截
include:
- /telInfo/**
- /vaccinationInfo/**
以上,就可以在vue中站着用history模式了



