spring - CORS 策略已阻止从源访问 XMLHttpRequest

标签 spring vue.js cors

我在使用 VueJS 和 Spring 时遇到 CORS 错误。 VueJS 使用 POST 调用 REST WS。我在下面尝试通过创建 CorsConfiguration 并添加来源、 header 和方法来允许 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.

Spring

@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);
    }
}

视觉

//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)
})

最佳答案

你能试试加行吗

corsConfiguration.setAllowCredentials(true);

因此你的代码看起来像

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

关于spring - CORS 策略已阻止从源访问 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53496336/

相关文章:

javascript - CORS 阻止本地文件加载另一个本地文件 - WTF?

jquery - JavaFX 2.2 中 WebView 并不真正支持 CORS?

java - 如何处理渲染 View 时抛出的异常

java - 我可以拥有多个具有 spring 安全性的安全上下文吗?

java - count() 方法之间的冲突 - CrudRepository - Spring

vue.js - 使用 vuex 和 vue-resource 预取数据

javascript - 导出默认值中 'name' 属性的目的/用途是什么{}

vue.js - 如何在 vue 中通过 vue-i18n 使用每种语言的多个文件?

javascript - 如何使用 Embark 框架演示程序运行 IPFS

java - JUnit 和 Spring 的 DAO 层测试策略