How to solve the problem of Ajax cross-domain and cookie failure in SpringBoot
When writing the login registration page of my own project, because my registration and password change functions use email verification, the backend will add a cookie to the response data when sending the verification code
Cookie cookie = new Cookie(toEmail.split("@")[0],verCode); cookie.setMaxAge(30*60); response.addCookie(cookie);
and then When you click to register or change your password, the backend will obtain the cookie from the request to obtain the email and verification code information
Cookie[] cookies = request.getCookies();
When testing locally, the cookie can be correctly added to the response and can also be obtained correctly
But when I packaged the project to the cloud and then performed ajax access, a problem occurred. Cookie acquisition failed!
There is clearly set-Cookie in the response header, but Cookie cannot be found in the second request header
The server fails to obtain the cookie and reports an error. The function of using cookies to register and change passwords is invalid. After searching for the document, I found that the error originated from the cross-domain cookie loss problem of springboot and ajax. Since I am new to the backend,
I only post my solution here
1. The ajax request needs to carry xmlhttp.withCredentials = true; #3. Set the response header for the response in the api in the Controller, key
is "Access-Control-Allow-Origin" access control allowed source, http request header information, set allowed resource sharing (cross-domain ) The sourcevar xmlhttp = new XMLHttpRequest(); xmlhttp.withCredentials = true; xmlhttp.open("GET", readyUrl, true); xmlhttp.send();
value is request.getHeader("Origin"), which represents the protocol and domain name
combination of the page where the currently requested resource is located Together they mean Allow the current requested resource to access back-end resources across domains
After setting these three parts, I can get the cookie again2022 -12-09 Update:
Found a more concise and convenient method to add a cross-domain request filterUsed the StringUtils.isEmpty method of the Druid data pool dependency package , if an error is reported, just write a replacement yourself
package com.crisp.myblog.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class corsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") //是否发送Cookie .allowCredentials(true) //放行哪些原始域 .allowedOriginPatterns("这里填你前端代码所在的域名:端口") .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) .allowedHeaders("*") .exposedHeaders("*"); } }
The above is the detailed content of How to solve the problem of Ajax cross-domain and cookie failure in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor
