开发中,如何解决跨域问题?

跨域问题
跨域问题是指浏览器在执行JavaScript代码的时候,由于浏览器同源策略的限制,只能访问同源的资源,不能跨域访问 。
解决跨域问题的两种方式:
jsonp(JSON with Padding)是json的一种使用模式,前端解决跨域问题的方法,只支持GET请求,需要后端提供jsonp接口CORS(Cross-Origin Resource Sharding)跨域资源共享,后端解决跨域问题的方法jsonp
原理:
本质就是利用<script>标签的src属性不受同源策略限制,请求跨域的数据接口 , 并通过函数调用的形式,接收跨域接口响应回来的数据 。
后端接口示例:
接口返回拼接的函数字符串,函数字符串的参数,就是返回给前端的数据 。
【开发中,如何解决跨域问题?】一个简单的jsonp请求:<body><script>function success(data) {console.log(&
在http响应头中设置允许跨域访问的特定字段,如
三种实现代码示例(这里代码基于springboot):
使用CorsFilter实现跨域访问:@Beanpublic CorsFilter corsFilter() {UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();CorsConfiguration config = new CorsConfiguration();config.setAllowCredentials(true);config.addAllowedOrigin(\”*\”);// config.addAllowedOrigin(\”https://www.example1.com\”);// config.addAllowedOriginPattern(\”https://*.example2.com\”);config.addAllowedHeader(\”*\”);config.addAllowedMethod(HttpMethod.OPTIONS);config.addAllowedMethod(HttpMethod.HEAD);config.addAllowedMethod(HttpMethod.PATCH);config.addAllowedMethod(HttpMethod.GET);config.addAllowedMethod(HttpMethod.POST);config.addAllowedMethod(HttpMethod.PUT);config.addAllowedMethod(HttpMethod.DELETE);source.registerCorsConfiguration(\”/**\”, config);return new CorsFilter(source);}使用 @CrossOrigin 注解@CrossOrigin(origins = \”https://www.example.com\”, methods = {RequestMethod.OPTIONS, RequestMethod.GET, RequestMethod.POST})@GetMapping(value = https://www.30zx.com/”/account/user/”)public Result getUserInfo(String sUserId) {}使用 WebMvcConfigurer 实现public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping(/”/**/”).allowedOrigins(/”https://www.example.com/”).allowedMethods(/”*/”);}}
以上就是朝夕生活(www.30zx.com)关于“开发中,如何解决跨域问题?”的详细内容,希望对大家有所帮助!

猜你喜欢