在实现文件下载的功能时,如果使用vue下载本项目的静态资源,则会遇到跨域的问题,从而不能下载。
所以,需要添加一些设置才能使得vue项目下载本项目中的资源。
在 config
下新建一个文件 WebConfig.java
,跨域设置如下:
package com.withered.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
/**
* 跨域请求处理,通过添加跨域请求映射实现
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 为指定路径开启跨域请求处理
.allowedOriginPatterns("*") // 允许所有域
.allowedMethods("*") // 允许任何方法(post、get等)
.allowedHeaders("*") // 允许任何请求头
.allowCredentials(true) // 允许证书、cookie
.maxAge(3600L); // 在3600秒内,不需要再发送预检验请求,可以缓存该结果
}
};
}
}