CORS策略已阻止对XMLHttpRequest的访问。

时间:2019-08-10 17:15:05

标签: angular spring-boot cors

我的应用程序具有前端前端和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

3 个答案:

答案 0 :(得分:0)

该问题可能是由于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");
    }
}

答案 1 :(得分:0)

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

Spring Boot Security CORS

答案 2 :(得分:0)

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

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

enter image description here