The front-end and back-end projects are separated, and the solution that the front-end cookie cannot be obtained

Recently, in writing the [front-end and back-end separation] project, it was found that after the back-end added cookies in the response

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

public class CorsConfig {

    // The maximum valid duration of the current cross-domain request. Here by default 1 day 
    private  static  final  long MAX_AGE = 24 * 60 * 60 ;

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials( true ); //allow to accept cookies 
        corsConfiguration.addAllowedOriginPattern( "*" ); // 1 set the access source address 
        corsConfiguration.addAllowedHeader( "*" ); // 2 set the access source request header 
        corsConfiguration.addAllowedMethod( " *" ); // 3 Set the access source request method
        return corsConfiguration;

    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration( "/**" , buildConfig()); // 4 pairs of interface configuration cross-domain settings 
        return  new CorsFilter(source);

The front end cannot get the cookie, but the cookie does exist in the network [capture]

But I can’t find the cookie in the Application

The solution to the problem was to set the Credentials property to true in the cross-domain config, which was not present in my cross-domain config at first.

Cross-domain file for backend configuration:"http://localhost:9090/login", this.form, {withCredentials: true})
        .then((res) => {}

Note: After adding corsConfiguration.setAllowCredentials(true);, put the original


Change it to:


Front-end configuration (here I use axios request):

One-time configuration:"http://localhost:9090/login", this.form, {withCredentials: true})
        .then((res) => {}

Unified configuration

axios.defaults.withCredentials = true;

After configuration, you can get the cookie

Leave a Comment

Your email address will not be published. Required fields are marked *