栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot中解决跨域问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot中解决跨域问题

1、设置response对象的header

response.addHeader(“Access-Control-Allow-Credentials”, “true”);
response.addHeader(“Access-Control-Allow-Origin”, “http://localhost:8080”);
response.addHeader(“Access-Control-Allow-Methods”, “POST, GET, OPTIONS,DELETE,PUT”);

2、 在controller类中添加@CrossOrigin注解

使用方法:

(1)在controller类方法上添加@CrossOrigin注解

@RestController
@RequestMapping("/review")
public class AccountController {
 
    @CrossOrigin
    @GetMapping("/{id}")
    public String retrieve(@PathVariable Long id) {
        // ...
    }
 
    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

(2)在整个controller类上添加@CrossOrigin

@CrossOrigin(origins = "http://pghhh.top", maxAge = 3600)
@RestController
@RequestMapping("/review")
public class AccountController {
 
    @GetMapping("/{id}")
    public String retrieve(@PathVariable Long id) {
        // ...
    }
 
    @DeleteMapping("/{id}")
    public void remove(@PathVariable Long id) {
        // ...
    }
}

@CrossOrigin中的两个参数:

  • origins: 允许可访问的域列表
  • maxAge:准备响应前的缓存持续的最大时间(以秒为单位)

通过这种方式,AccountController类下的所有方法都启用了跨域支持。

(3)如果使用了Spring Security,可以在Spring Security中进行配置

请确保在Spring安全级别启用CORS,并允许它利用Spring MVC级别定义的配置。

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}
3、全局CORS配置

基于WebMvcConfigurerAdapter配置加入Cors的跨域

import org.springframework.context.annotation.Configuration; 

import org.springframework.web.servlet.config.annotation.CorsRegistry; 

import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 

@Configuration 

public class CorsConfig extends WebMvcConfigurerAdapter { 
    
    
    @Override 

    public void addCorsMappings(CorsRegistry registry) { 
    
        registry.addMapping("/**") // 所有的当前站点的请求地址,都支持跨域访问

               .allowedOriginsPatterns("*") // 所有的外部域都可跨域访问。 如果是localhost则很难配置,因为在跨域请求的时候,外部域的解析可能是localhost、127.0.0.1、主机名(注意:SpringBoot2.4.0之后【allowedOriginsPatterns】代替【allowedOrigins】)
            
               .allowCredentials(true) // 是否支持跨域用户凭证

               .allowedMethods("GET", "POST", "DELETE", "PUT") // 当前站点支持的跨域请求类型是什么
            .maxAge(3600); // 超时时长设置为1小时。 时间单位是秒
    } 
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602962.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号