当前位置:网站首页>There is a problem with CORS cross domain request
There is a problem with CORS cross domain request
2022-04-21 20:07:00 【A brave man who muddles along y】
1、 Problem description
Access to XMLHttpRequest at ‘http://localhost:8080/user/register’ from origin ‘http://localhost:8002’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
The specific situation is the front and rear end separation project , The back end has been added to the controller @CrossOrigin annotation , However, there is still a cross domain problem when the front end requests the back-end interface
2、 Problem tracing
The front-end code :
this.$http({
url: this.$http.adornUrl('/user/register'),
method: 'post',
headers:{
"Content-Type": 'application/json;charset=utf-8', // solve 415 problem
},
data: JSON.stringify(params)
}).then()
axios To configure :
const http = axios.create({
timeout: 1000 * 30,
withCredentials: true, // If the current request is a cross domain type, whether to co bring... In the request cookie
})
Background code :
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService iUserService;
@PostMapping("register")
public Result register(@RequestBody UserBody userBody) {
return iUserService.register(userBody);
}
}
First, the request parameters of the background controller use **@RequestBody This annotation **, This needs to be Front end incoming json Formatted data
Because of the front end form The default parameter transfer method of the form is application/x-www-form-urlencoded, Therefore, when requesting the back-end interface, there will be Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported A request for such data contentType Inconsistent with the backend 415 error
So I'm at the front In the request... Is set "Content-Type": 'application/json;charset=utf-8' Such a request header to resolve this error
tips: Adding the request header makes the request become Complex request ( See below )
options A request is a pre check request , Can be used to detect what the server allows http Method . When a cross domain request is initiated , For safety reasons , When a certain condition is triggered, the browser will automatically initiate before the formal request OPTIONS request , namely CORS Pre inspection request , If the server accepts the cross domain request , The browser continues to make formal requests .
This is in the case of cross domain , Browser initiation " Complex request " It was initiated on its own initiative . Cross domain sharing standards and specifications require , For those that may have side effects on server data HTTP Request method ( especially GET Outside of the HTTP request , Or something MIME Type of POST request ), Browsers must first use OPTIONS Method to initiate a pre check request (preflight request), So we can know whether the server allows the cross domain request . After the server confirms the permission , To launch the actual HTTP request .
Some requests don't trigger CORS Pre inspection request , Such a request is generally called “ A simple request ” , The request that will trigger the pre inspection is “ Complex request ” .
A simple request- The request method is GET、HEAD、POST Time's request ;
- Consider setting the header field within the specification set , Such as Accept/Accept-Language/Content-Language/Content-Type/DPR/Downlink/Save-Data/Viewport-Width/Width;
- Content-Type Is limited to one of the following three values , namely application/x-www-form-urlencoded、multipart/form-data、text/plain;
- Arbitrary in the request XMLHttpRequestUpload Object does not register any event listeners ;
- Not used in the request ReadableStream object
Complex request- PUT/DELETE/CONNECT/OPTIONS/TRACE/PATCH;
- Artificially set the header field outside of the following set , That is, the fields outside the simple request ;
- Content-Type The value of is not one of the following , namely application/x-www-form-urlencoded、multipart/form-data、text/plain.
However, it solved 415 After the problem , The request still failed , This time it became CORS error , That's the mistake shown at the beginning
Looking up the data, I found CORS The request is not sent by default Cookie and HTTP Authentication information , If you want to put the Cookie Send to server , On the one hand, the server should agree to , Appoint Access-Control-Allow-Credentials Field , On the other hand , The developer must be in AJAX Open in request withCredentials attribute . otherwise , Even if the server agrees to send Cookie, Browsers don't send . perhaps , The server requires settings Cookie, The browser doesn't handle . Obviously carry... In the request cookie Obviously, it is a very common operation , So I am axios Enabled in settings withCredentials Set up
Here's the problem. If you want to send Cookie,Access-Control-Allow-Origin It can't be set as an asterisk , There must be a definite 、 Domain name consistent with the requested page
This is the meaning expressed in the error message of the page console
3、 summarizing
- Current end configuration
withCredentials=truewhen , The backend configurationAccess-Control-Allow-OriginNot for*, Must be the corresponding address - When configuring
withCredentials=truewhen , The backend needs to be configuredAccess-Control-Allow-Credentials - When configuring the request header at the current end , The backend needs to be configured
Access-Control-Allow-HeadersSet the corresponding request headers- This field is optional .CORS When asked ,XMLHttpRequest Object's getResponseHeader() Methods can only get 6 Basic fields :Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma. If you want to get other fields , Must be in Access-Control-Expose-Headers Specify the inside .
namely =》 If cross domain needs to be carried cookie To request ,Access-Control-Allow-Credentials It has to be for true, But be careful when Access-Control-Allow-Credentials=true when ,Access-Control-Allow-Origin You can't do it for me ” * “ , Must be a clear domain name
The back end needs to return Header What are they? ?
# The domain name allowed by the server
Access-Control-Allow-Origin=https://idss-uat.jiuyescm.com
# The server allows access to Http Method
Access-Control-Allow-Methods=GET, POST, PUT, DELETE, PATCH, OPTIONS
# The server accepts the cross domain Cookie, When it comes to true when ,origin The domain name must be clear and cannot be used *
Access-Control-Allow-Credentials=true
# Access-Control-Allow-Headers Indicates that it allows cross domain requests to contain content-type head
Access-Control-Allow-Headers=Content-Type,Accept
# Pre check requests in cross domain requests (Http Method by Option) The validity of the ,20 God , Unit second
Access-Control-Max-Age=1728000
4、 Encapsulated as a configuration class
@Configuration
public class WebConfig implements WebMvcConfigurer {
// Interceptor cross domain configuration
@Override
public void addCorsMappings(CorsRegistry registry) {
/* // Cross domain paths CorsRegistration cors = registry.addMapping("/**"); // Accessible external domains cors.allowedOrigins("http://localhost:8002"); // Support cross domain user credentials cors.allowCredentials(true); cors.allowedOriginPatterns("*"); // Set up header Information that can be carried cors.allowedHeaders("*"); // Set the request method that supports cross domain cors.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION"); // Set cross domain expiration time cors.maxAge(3600); */
registry.addMapping("/**")
.allowedOrigins("http://localhost:8002")
.allowCredentials(true)
.allowedOriginPatterns("*")
.allowedHeaders("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTION")
.maxAge(3600);
}
}
版权声明
本文为[A brave man who muddles along y]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211930157006.html
边栏推荐
- 如何判斷Int型值的第nbit比特是否是1還是0
- Efficient C language memory copy Test result Rand, loop, operator =% in x86-64 SUSE
- Nodejs notes 1
- Jerry's interrupt list [chapter]
- 长安深蓝C385产品信息曝光 瞄准20万级别,头号目标Model 3!
- First acquaintance with EEMBC coremark
- Paraview grace startup error
- Registration for PMP examination starts in the second half of 2022. Notice
- Why does SVPWM module have sector judgment error?
- Gbase 8A set group_ concat_ max_ Solution to error reporting after len parameter
猜你喜欢

Yijia announced that its products will enter oppo stores in the future and will launch the group's new resources

【2021】腾讯秋招技术岗编程 有效序列的数量

危化品企业双预防机制数字化建设综合解决方案

Discussion on the hot and cold issues of open source license grounding gas

CUDA02 - 访存优化和Unified Memory

Dolphin DB vscode plug-in tutorial

80. (leaflet chapter) leaflet calls the PostGIS data layer published by GeoServer

How does the Mui tab realize circular rotation

Introduction to applet project files

如何在不加锁的情况下解决线程安全问题
随机推荐
【玩转Lighthouse】使用腾讯云轻量实现微信支付业务
[play with lighthouse] use Tencent cloud to realize wechat payment business in light weight
Jerry's switch interrupt function using unshielded interrupt [chapter]
开源许可证热门及冷门问题接地气探讨
Multi factor strategy
GBase 8a设置 group_concat_max_len 参数后报错解决方案
HW - new employee examination - traversal
B / s interface control devextreme ASP Net MVC Getting Started Guide - template syntax (I)
Wild road play QT, episode 31, glass cleaning game
PyCharm failed to create JVM
Instructions for Jerry's reset IO maintenance level [chapter]
How to let the back door of the network card kill a system and let you know how powerful the network card is
Digital business cloud community property platform system solution - easy property management and leveraging potential business opportunities
《常识题题库系统》,公务员必备,博学广识之士必备。从程序员变成诗人
创建索引的注意事项
Unity Socket
Dolphin DB vscode plug-in tutorial
联想公布ESG新进展:承诺2025年全线计算机产品100%含有再生塑料
Meaning of stripe in image
【verbs】使用ibverbs api注意事项|libibverbs 中 fork() 支持的状态如何?