当前位置:网站首页>Solutions to cross domain problems
Solutions to cross domain problems
2022-07-07 12:20:00 【YXXYX】
introduction
Cross domain problems are usually encountered in projects with front end and back end separation , Cross domain arises because browsers are set up for security The same-origin policy , Only agreement (http/https)、 domain name (www.test.com)、 port (8080/8081…) When the three are the same, cross domain problems will not occur ;
This also explains why there are cross domain problems in projects with front-end and back-end separation , For example, we develop on the same server , Front-end url by :http://127.0.0.1:3000, And the back end url by :http://127.0.0.1:8080, Both ports are different. If you visit each other, cross domain problems will certainly occur ;
Pictured :

front end http://localhost:3000 Send a request back :http://localhost:8080/api/user/search/tags, But because the port number is different , So the request failed , The error message also shows cross domain policy blocking :has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Now let's share my solutions to cross domain problems ;
resolvent
Here are several ways to solve the above case ;
WebMvcConfig Configuration class cross domain configuration
Cross domain requests can be implemented through custom configuration classes , The specific configuration is as follows :
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// Set the allowed cross domain paths
registry.addMapping("/**")
// Set the domain name that allows cross domain requests
// When Credentials The certificate is true when ,Origin It can't be an asterisk , It needs to be specific ip Address ( If the interface doesn't have cookie,ip You don't need to be specific ip)
.allowedOrigins("http://localhost:3000")
// Whether to allow certificates No longer default on
.allowCredentials(true)
// Set allowed methods
.allowedMethods("*")
// Cross domain allow time
.maxAge(3600);
}
}
The front end requests from the back end :

You can see that the request succeeded , And cross domain allowed url The front-end domain name configured for :http://localhost:3000
annotation @CrossOrigin Achieve cross-domain
This method is much simpler than the above method , Directly on the back end Controller Add this annotation to the class , By default, all cross domain requests are allowed , But it's better to indicate the requested domain name :

This also enables cross domain access , It's simpler than configuration , But there are drawbacks , The last one says ;
The result is not to show , Same as before ;
GateWay Gateway configuration
The gateway configuration is generally a separate gateway module in the microservice project , Because all requests in microservices must be filtered through the gateway , So the first request is to go to the gateway , We can configure cross domain in the gateway service :
In the gateway module application.yml Configure cross domain in the configuration file :
# Cross domain configuration :
spring:
cloud:
gateway:
globalcors: # Global cross domain processing
add-to-simple-url-handler-mapping: true # solve options The request is blocked
corsConfigurations:
'[/**]': # Set which requests to block ,/** Means to intercept all requests
allowedOrigins: # Allow cross domain requests for which websites
- "http://localhost:3000"
allowedMethods: # Allowed cross domain ajax Request method of
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # Header information allowed to be carried in the request
allowCredentials: true # Is it allowed to carry cookie
maxAge: 360000 # The validity period of this cross domain detection
We can also customize the configuration file configuration :
/** * Cross domain unified configuration */
@Configuration
public class CorsConfig {
// To deal with cross domain
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
// Allowed request header
config.addAllowedMethod("*");
// Allowed request sources ( Such as :http://localhost:8080)
config.addAllowedOrigin("http://localhost:3000");
// The allowed request method ==> GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
config.addAllowedHeader("*");
// URL mapping ( Such as : /admin/**)
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
Both of these methods can realize the cross domain configuration of the gateway ;
summary
In general, three methods to solve cross domain problems are introduced , So how to choose actually ?
@CrossOrigin annotation : This method is suitable for individual projects , More flexible , Implement a simple ; every last Controller Cross domain allowed by interface url All very clear. , however Controller It's troublesome when there are many interfaces ;
WebMvcConfig Configuration class : This method is suitable for individual projects , And if you feel in every Controller Add @CrossOrigin If annotation is troublesome , You can use this method ;
GateWay Gateway configuration : This method is suitable for microservice projects , And the two methods I share are still relatively recommended to use the first method , Directly in application.yml File configuration ;
One thing to note : If the gateway is configured with cross domain , then Don't Configure cross domain elsewhere , For example, in Controller add @CrossOrigin annotation , If you cross domains like this, it is equivalent to no configuration , It will fail ;
边栏推荐
- Cenos openssh upgrade to version 8.4
- Xiaohongshu microservice framework and governance and other cloud native business architecture evolution cases
- H3C HCl MPLS layer 2 dedicated line experiment
- Common locking table processing methods in Oracle
- Flet教程之 18 Divider 分隔符组件 基础入门(教程含源码)
- wallys/Qualcomm IPQ8072A networking SBC supports dual 10GbE, WiFi 6
- Completion report of communication software development and Application
- The road to success in R & D efficiency of 1000 person Internet companies
- Fleet tutorial 15 introduction to GridView Basics (tutorial includes source code)
- Mastering the new functions of swiftui 4 weatherkit and swift charts
猜你喜欢

Flet tutorial 17 basic introduction to card components (tutorial includes source code)

【纹理特征提取】基于matlab局部二值模式LBP图像纹理特征提取【含Matlab源码 1931期】

数据库系统原理与应用教程(009)—— 概念模型与数据模型

Programming examples of stm32f1 and stm32subeide -315m super regenerative wireless remote control module drive

从工具升级为解决方案,有赞的新站位指向新价值

超标量处理器设计 姚永斌 第9章 指令执行 摘录
![110. Network security penetration test - [privilege promotion 8] - [windows sqlserver xp_cmdshell stored procedure authorization]](/img/62/1ec8885aaa2d4dca0e764b73a1e2df.png)
110. Network security penetration test - [privilege promotion 8] - [windows sqlserver xp_cmdshell stored procedure authorization]

Sign up now | oar hacker marathon phase III midsummer debut, waiting for you to challenge

软件内部的定时炸弹:0-Day Log4Shell只是冰山一角
![111. Network security penetration test - [privilege escalation 9] - [windows 2008 R2 kernel overflow privilege escalation]](/img/2e/da45198bb6fb73749809ba0c4c1fc5.png)
111. Network security penetration test - [privilege escalation 9] - [windows 2008 R2 kernel overflow privilege escalation]
随机推荐
College entrance examination composition, high-frequency mention of science and Technology
【神经网络】卷积神经网络CNN【含Matlab源码 1932期】
Cmu15445 (fall 2019) project 2 - hash table details
Inverted index of ES underlying principle
Flet教程之 17 Card卡片组件 基础入门(教程含源码)
[neural network] convolutional neural network CNN [including Matlab source code 1932]
开发一个小程序商城需要多少钱?
源代码防泄密中的技术区别再哪里
powershell cs-UTF-16LE编码上线
110. Network security penetration test - [privilege promotion 8] - [windows sqlserver xp_cmdshell stored procedure authorization]
18 basic introduction to divider separator component of fleet tutorial (tutorial includes source code)
[filter tracking] comparison between EKF and UKF based on MATLAB extended Kalman filter [including Matlab source code 1933]
<No. 9> 1805. Number of different integers in the string (simple)
Unity中SmoothStep介绍和应用: 溶解特效优化
MATLAB实现Huffman编码译码含GUI界面
Problem: the string and characters are typed successively, and the results conflict
千人规模互联网公司研发效能成功之路
Explore cloud database of cloud services together
软件内部的定时炸弹:0-Day Log4Shell只是冰山一角
How to connect 5V serial port to 3.3V MCU serial port?