cors
CORS,全称Cross-Origin Resource Sharing ,是一种允许当前域(domain)的资源被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求。
配置类CorsConfig
package com.base.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @ClassName CorsConfig
* @Decription
* @Author Kalinda
* @Date 2020/1/29 8:57
* @Version 1.0
**/
@Configuration
public class CorsConfig {
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);
}
}
测试controller
package com.base.cors.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName TestController
* @Decription
* @Author Kalinda
* @Date 2020/1/29 9:02
* @Version 1.0
**/
@RestController
public class TestController {
@RequestMapping("/test")
public int test() {
return 1;
}
}
前端访问
<template>
<div>
<el-button plain @click="testCors">测试跨域</el-button>
</div>
</template>
<script>
let baseUrl = 'http://localhost:8989'
export default {
name: "TestCors",
methods: {
testCors() {
this.$http({
url: baseUrl + "/test",
methods: "post",
})
.then(response => {
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
}
}
}
访问成功

本文详细介绍了CORS(跨域资源共享)的概念及其在Spring框架中的实现方式。通过配置CorsConfig类,允许不同域间的资源访问,解决了浏览器的同源策略限制。同时,提供了后端Controller和前端Vue.js的示例代码,展示了如何进行跨域请求。
2586

被折叠的 条评论
为什么被折叠?



