当前位置:网站首页>跨域问题(CORS)详细说明和解决
跨域问题(CORS)详细说明和解决
2022-07-22 04:56:00 【程序员blingbling】
一.什么是跨域问题
就是浏览器对JS施加的一种安全限制.浏览器默认不允许JS脚本获取远程网站的数据.
当JS发送AJAX请求时,就要遵守同源策略,否则会被限制.
此外,通过img、iframe、script等标签的src属性,则不限制。主要限制不同源网站相互之间的ajax调用。
二.跨域请求的流程
针对一些非简单的跨域请求,浏览器会先发送一个预检请求(请求方法为OPTIONS),也就是询问服务器是否允许这样的跨域请求,如果浏览器允许,
才会发送真正的数据请求.
什么是非简单的请求?
某些请求不会触发 CORS 预检请求。本文称这样的请求为“简单请求”,若请求 满足所有下述条件,则该请求可视为“简单请求”:
三.跨域问题的体现
如果你的请求出现如下报错,那就是出现了跨域问题
四.跨域问题解决
1.使用nginx统一代理
我们可以将前端项目也部署到nginx服务器中,然后所有的请求均由nginx进行统一转发,从而解决跨域问题.
2.配置当前请求允许跨域.
既然跨域会发送预检请求,那么我们只要在后端配置允许当前请求可以跨域不就可以了吗.
我们可以在后端设置添加请求头进行返回,也就是配置一个filter,就可以实现跨域请求配置.
举例:
@Configuration
public class CronConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//允许带哪些请求头的请求跨域
corsConfiguration.addAllowedHeader("*");
//允许哪些请求方法跨域
corsConfiguration.addAllowedMethod("*");
//允许哪些请求来源跨域
corsConfiguration.addAllowedOrigin("*");
//是否允许携带cookie跨域
corsConfiguration.setAllowCredentials(true);
//针对任意路径均进行跨域配置
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}
今天的分享就到这里了,有问题可以在评论区留言,均会及时回复呀.
我是bling,未来不会太差,只要我们不要太懒就行, 咱们下期见.
边栏推荐
- What are the requirements for docking with the third-party payment interface?
- AlterNet Studio 8.1 Crack
- 盘点 | 2022年上半年国内的电邮安全事件
- UE4 键盘按键实现开关门
- AT4162 [ARC099C] Independence
- Regular expression correlation
- BUUCTFReservewp(3)
- Kingbasees Security Guide for Jincang database -- 2.1. about database security threats
- How to solve the problem of win10? The app store cannot be opened, and the error code is 0x80131500
- Gold warehouse database kmonitor usage guide --2. monitoring indicators
猜你喜欢
随机推荐
Pixels and colors
Concis组件库 | 暗黑模式设计
梅科尔工作室——HarmonyOs第二次作业
TensorFlow 各优化器在鸢尾花分类任务中的应用
AlterNet Studio 8.1 Crack
ARC110F Esoswap
When the win10 system is turned on, the response is slower than usual. How to solve it by turning around and waiting for 1 minute?
欠拟合与过拟合 (正则化)
UE4 创建一个工程
The function and application of tostring() and rewriting
[leetcode weekly race -- hash table number pairs] 6164. Maximum sum of digit and equal number pairs
Bryntum Scheduler Pro 5.0.6 \Gantt\Crack
解析参与机器人教育竞赛的热潮
PHP QR code decoding qrreader class | QR code image to string
CF1635F Closest Pair
BUUCTFReservewp(3)
把握机器人教育朝AI智能化发展的趋势
Rsync downlink synchronization +inotify real-time synchronization deployment
使用ffmpeg推流拉流
Chaque jour - jour 41 - 125. Vérifier la chaîne de palindromes