1.后端配置新建一个CrosConfig.java文件(配置类),允许任意请求发送importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;
1. 后端配置
新建一个CrosConfig.java文件(配置类),允许任意请求发送
| import org.springframework.context.annotation.Bean; |
| import org.springframework.context.annotation.Configuration; |
| import org.springframework.web.cors.CorsConfiguration; |
| import org.springframework.web.cors.UrlBasedCorsConfigurationSource; |
| import org.springframework.web.filter.CorsFilter; |
| import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; |
| |
| |
| |
| |
| |
| |
| @Configuration |
| public class CrosConfig implements WebMvcConfigurer { |
| |
| |
| @Bean |
| public CorsFilter corsFilter() { |
| CorsConfiguration config = new CorsConfiguration(); |
| config.addAllowedOrigin("*"); |
| config.addAllowedMethod("*"); |
| config.addAllowedHeader("*"); |
| UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); |
| configSource.registerCorsConfiguration("/**", config); |
| return new CorsFilter(configSource); |
| } |
| } |
2. 前端配置代理(前后端只要一个配置就行)
vue根目录下新建一个 vue.config.js 文件
| |
| module.exports = { |
| devServer: { |
| proxy: 'http://localhost:5000' |
| } |
| } |
- 优点:配置简单,请求资源时直接发给前端(8080)即可。
- 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
- 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源,即当前端存在请求的东西时,则直接返回前端的东西)
| |
| module.exports = { |
| devServer: { |
| proxy: { |
| '/api': { |
| target: 'http://localhost:5000', |
| changeOrigin: true, |
| pathRewrite: {'^/api': ''} |
| }, |
| '/api2': { |
| target: 'http://localhost:5001', |
| changeOrigin: true, |
| pathRewrite: {'^/api2': ''} |
| } |
| } |
| } |
| } |
| |
| |
| |
| |
| |
- 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
- 缺点:配置略微繁琐,请求资源时必须加前缀