spring - 从源访问 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)
})
解决方案
您可以尝试添加该行吗
corsConfiguration.setAllowCredentials(true);
因此你的代码看起来像
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
推荐阅读
- javascript - 将纹理放在 obj 文件上
- apache-spark - 火花连接问题
- javascript - 使用自定义视图在 columnrange highcharts 中对类别进行分组
- angular - .detectChanges() not working within Angular test
- r - 如果变量名称的格式不一致,如何更正/标准化变量名称
- spring-integration - 用于在流程中存储和检索的弹簧集成 dsl 流程变量
- algorithm - 寻找复杂性的下限和上限
- firebase - 每个设备和消息的 fcm 配额和限制
- javascript - 正则表达式在句子中定义捕获的组
- javascript - 根据从选择框中选择的值过滤特定的表列