从源头开始对XMLHttpRequest的访问已被CORS策略阻止

时间:2018-11-27 09:21:21

标签: spring vue.js 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)
})

1 个答案:

答案 0 :(得分:0)

您可以尝试添加行

corsConfiguration.setAllowCredentials(true);

因此您的代码将如下所示

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