首页 > 解决方案 > 从源访问 XMLHttpRequest 已被 CORS 策略阻止

问题描述

我在使用 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)
})

标签: springvue.jscors

解决方案


您可以尝试添加该行吗

corsConfiguration.setAllowCredentials(true);

因此你的代码看起来像

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

推荐阅读