从源访问 XMLHttpRequest 已被 CORS 策略阻止

Posted

技术标签:

【中文标题】从源访问 XMLHttpRequest 已被 CORS 策略阻止【英文标题】:Access to XMLHttpRequest at from origin has been blocked by CORS policy 【发布时间】:2019-04-28 23:55:21 【问题描述】:

我在使用 VueJS 和 Spring 时遇到 CORS 错误。 VueJS 使用 POST 调用 REST WS。我在下面尝试通过创建 CorsConfiguration 并添加源、标头和方法来允许 CORS,但它没有用。感谢您的帮助。

浏览器

OPTIONS https://test/example/ 403

Access to XMLHttpRequest at 'https://test/example/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

春天

@Configuration
public class CustomCORSConfiguration 

    private CorsConfiguration buildConfig() 
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    

    @Bean
    public CorsFilter corsFilter() 
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    

Vue

//POST
const config = 
    headers: 
        'Content-Type': 'application/json'
    ,
    strictSSL: false,
    changeOrigin:true,
    rejectUnauthorized: true,//add when working with https sites
    requestCert: false,//add when working with https sites
    agent: false//add when working with https sites

const reqBody = 
        "shopCode": "ASCDASDCASD",
        "amount": this.total_price,
        "authToken": "EDSAACDSAD"


this.axios.post(api, reqBody, config).then(response => 
    if (response) 
        const data = response.data
        console.log(data)
        this.qrUrl = data.data
         console.log(this.qrUrl)
        //if (this.qrUrl) 
           // this.loading=false
            location.href = this.qrUrl
        //
    
).catch(e => 
    this.errors=e
    alert(e)
    console.log(this.errors)
)

【问题讨论】:

【参考方案1】:

你可以尝试添加行吗

corsConfiguration.setAllowCredentials(true);

因此你的代码看起来像

CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");

【讨论】:

以上是关于从源访问 XMLHttpRequest 已被 CORS 策略阻止的主要内容,如果未能解决你的问题,请参考以下文章

从源“http://localhost:4200”访问“”处的 XMLHttpRequest 已被 CORS 阻止。我无权访问服务器

从源“http://localhost:3000”访问“https://***”处的 XMLHttpRequest 已被 CORS 策略阻止

从源“http://localhost:4200”访问“http://localhost:1111/...”的 XMLHttpRequest 已被 CORS 策略阻止:

从源“http://localhost:62521”访问“localhost:3000/users”的 XMLHttpRequest 已被 CORS 策略阻止

从源“null”访问“http://github/..file.json”处的 XMLHttpRequest 已被 CORS 策略阻止:

从源“http://localhost:4200”访问“localhost:8088/user/”的 XMLHttpRequest 已被 CORS 策略阻止 [重复]