当我们进行不同的ip地址或者不同的协议请求数据的时候,就会报跨域错误。然后我们可以使用下面的解决方案解决跨域的问题。
后端
1.在SpringSecurity配置类中配置http.cors(),还有关闭跨域攻击http.csrf().disable()
/**
* 自定义SpringSecurity配置类
*/
@Configuration
public class MySecurityConfigure extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 解决跨域问题
http.cors();
http.authorizeRequests()
.mvcMatchers("/test").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout()
.logoutUrl("/tuichu")
.logoutSuccessHandler(new LogoutSuccessHandler())
.and()
.exceptionHandling().authenticationEntryPoint((request, response, ex) -> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().println("请认证之后在操作");
}).and().csrf().disable();
http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
然后创建config包,添加一个跨域配置
package cn.guan.config;
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 CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOriginPatterns("*")
// 是否允许cookie
.allowCredentials(true)
// 设置允许的请求方式
.allowedMethods("GET", "POST", "DELETE", "PUT")
// 设置允许的header属性
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
}
}
前端
这个配置可以不配也可以解决跨域的问题
处理跨域:都配上
在vite配置文件中配置proxy
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), WindiCSS()],
resolve: {
alias: {
"~": path.resolve(__dirname,'src')
}
},
// 配置前端服务地址和端口
server: {
host: '0.0.0.0',
port: 8991,
// 是否开启 https
https: false,
},
proxy: {// 跨域代理
'/apis': {
// target: 'http://' + env.VUE_APP_BASE_API,
target: 'http://localhost:8080', //
changeOrigin: true,
rewrite: (path) => path.replace(/^\/apis/, '')
},
// 代理 WebSocket 或 socket
// '/socket.io': {
// target: 'ws://localhost:3000',
// ws: true
// }
}
})
然后axios配置使用代理
// 1.引入axios实例
import axios from "axios";
// 2.构件一个axios实例
const service = axios.create({
baseURL: '/apis'
})
// 3.导出请求实例
export default service