跨域问题
跨域问题是指浏览器在执行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
以上就是朝夕生活(www.30zx.com)关于“开发中,如何解决跨域问题?”的详细内容,希望对大家有所帮助!
猜你喜欢
- 打破ajax 跨域问题,游刃有余的解决方案,大神就是这样操作的
- 剑网3攻略之挂机刷书!免费点卡这样用?玩家直呼:薅羊毛真香
- 听说你在剑网3做资历人?那你一定很快乐吧?
- 解决网站404页面返回200状态码问题
- VUE项目打包发到Docker二次刷新页面报404错误问题解决
- 佟丽娅陈思诚离婚了,这其中发生了什么?
- 磁盘被写保护怎么解除?取消写保护状态,只需这几步
- 移动硬盘无法访问怎么办?这3个方法可解决!
- SD卡变成RAW格式怎么办?怎么恢复数据?