Vue3+Ts+SpringBoot 跨域问题
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue3+TypeScript项目中,如果你遇到与Spring Boot后端的跨域问题,可以尝试以下方法解决:
- CORS配置: 在Spring Boot应用中,你可以添加CORS配置来允许特定的域进行跨域请求。
 
@Configuration
public class WebConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080") // 允许的域,修改为你的前端服务地址
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}- 注解: 在Spring Controller的方法或类上使用
@CrossOrigin注解,允许跨域请求。 
@RestController
@CrossOrigin(origins = "http://localhost:8080") // 允许的域,修改为你的前端服务地址
public class YourController {
    // ...
}- Nginx配置: 如果你使用Nginx作为反向代理,可以在Nginx配置中添加相应的CORS配置。
 
location / {
    proxy_pass http://backend;
    proxy_set_header Origin '';
    proxy_set_header Access-Control-Allow-Origin 'http://localhost:8080'; // 修改为你的前端服务地址
    proxy_set_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    proxy_set_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    proxy_set_header Access-Control-Allow-Credentials 'true';
    add_header 'Access-Control-Allow-Origin' 'http://localhost:8080' always; // 修改为你的前端服务地址
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization' always;
}确保将以上代码中的"http://localhost:8080"替换为你的实际前端服务地址。
以上方法可以解决跨域问题,但请注意,根据你的具体部署环境和安全策略,可能需要额外的配置或考虑。
评论已关闭