【问题标题】:Access to XMLHttpRequest at Access to XMLHttpRequest has been blocked by CORS policy访问 XMLHttpRequest 时访问 XMLHttpRequest 已被 CORS 策略阻止
【发布时间】:2019-12-18 00:41:25
【问题描述】:

我的应用程序有角度前端和 springboot 后端。 当我从前端 (localhost:4200) 调用后端 api (localhost:8080/test) 时,它给出了一个错误。

Access to XMLHttpRequest at http://localhost:8080/api/XXX/1 from origin http://localhost:4200 has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. 
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我的请求听众信息如下,

Request URL: http://localhost:8080/api/testSuite/execute/1
Referrer Policy: no-referrer-when-downgrade
Provisional headers are shown
Accept: application/json
Content-Type: application/json
Referer: http://localhost:4200/testSuite
Sec-Fetch-Mode: cors
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36

【问题讨论】:

  • 那么你是否在 Spring 中为前端启用了 CORS?
  • 在后端启用 CORS,并且不要忘记允许 OPTIONS 请求,因为浏览器会在飞行前发送一个。

标签: angular spring-boot cors


【解决方案1】:

此问题可能是由于 CSRF 保护造成的。 要禁用 CSRF 保护,您可以使用以下命令:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig
    extends WebSecurityConfigurerAdapter implements ApplicationContextAware {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .csrf().disable(); //add this
    }

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
        authManagerBuilder
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN");
    }
}

【讨论】:

  • 这适用于 springboot 1.5 版,但是当我升级到 2 时会发生此错误。
【解决方案2】:

在 Api 中允许 cors 请求标头以获取更多详细信息,请参阅下面的链接。

Spring Boot Security CORS

【讨论】:

    【解决方案3】:

    我的团队尝试了我们在互联网上可以找到的所有东西,但最后 Mozilla 的建议奏效了。请找到链接: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Preflighted_requests

    我们在随附的屏幕截图中尝试了这种方法,它对我们有用:

    【讨论】:

    • 欢迎来到 StackOverflow。请不要将图像用于容易以文本形式传达的信息。图片不适合搜索、复制和粘贴或视障人士。
    猜你喜欢
    • 2019-04-28
    • 2021-10-05
    • 2022-08-14
    • 2021-10-11
    • 2020-05-05
    • 2022-01-01
    • 2020-11-23
    • 2021-01-14
    相关资源
    最近更新 更多