Home > Java > javaTutorial > What are the cross-domain solutions for SpringBoot projects?

What are the cross-domain solutions for SpringBoot projects?

WBOY
Release: 2023-05-19 12:43:06
forward
1938 people have browsed it

Test whether it is cross-domain

You can open the console of a page in the browser, and then execute the following code in the console:

var xhr = new XMLHttpRequest()
xhr.open('GET', 'http://localhost:8080/user') // 替换请求的方法和地址
xhr.send()
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText)
    }
}
Copy after login

If the following output appears, It means that there is indeed cross-domain

What are the cross-domain solutions for SpringBoot projects?

1. SpringBoot configures CORS to solve cross-domain

That is, in all our response header configurations to allow cross-domain access, CORS has also become Mainstream cross-domain solution.

  • Create a new configuration file in the project

  • Add@ConfigurationAnnotation implementationWebMvcConfigurerInterface

  • Rewrite the addCorsMappings method and set the code that allows cross-domain

The specific code is as follows:

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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOriginPatterns("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
Copy after login

2. SpringBoot solves cross-domain access through CorsFilter

This method is similar to the above method, and also configures cross-domain access through Java Config. The specific code is as follows:

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;
@Configuration
public class MyCorsFilter {
    @Bean
    public CorsFilter corsFilter() {
        // 1.创建 CORS 配置对象
        CorsConfiguration config = new CorsConfiguration();
        // 支持域
        config.addAllowedOriginPattern("*");
        // 是否发送 Cookie
        config.setAllowCredentials(true);
        // 支持请求方式
        config.addAllowedMethod("*");
        // 允许的原始请求头部信息
        config.addAllowedHeader("*");
        // 暴露的头部信息
        config.addExposedHeader("*");
        // 2.添加地址映射
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
        corsConfigurationSource.registerCorsConfiguration("/**", config);
        // 3.返回 CorsFilter 对象
        return new CorsFilter(corsConfigurationSource);
    }
}
Copy after login

3. SpringBoot solves cross-domain issues through annotations

can be added to our controller class or controller method. Adding it to the class means that all methods in it can be cross-domain. Adding it to the method Indicates that the specified method can cross domains. The specific code is as follows:

import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @GetMapping
    public String getAll() {
        return "成功";
    }
}
Copy after login

4. Configure CORS through nginx to solve cross-domain issues

If our project is usefulnginx When doing a reverse proxy server , you can also configure CORS in nginx to solve cross-domain issues. The configuration example is as follows:

1. Allow all domain names

server {
    ...
    location / {
        #允许 所有头部 所有域 所有方法
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}
Copy after login

2. Allow Specify domain name

map $http_origin $corsHost {
    default 0;
    "~https://aa.cn" https://aa.cn;
    "~https://bb.cn" https://bb.cn;
    "~https://cc.cn" https://cc.cn;
}
server {
    ...
    location / {
        #允许 所有头部 所有$corsHost域 所有方法
        add_header 'Access-Control-Allow-Origin' $corsHost;
        add_header 'Access-Control-Allow-Headers' '*';
        add_header 'Access-Control-Allow-Methods' '*';
        #OPTIONS 直接返回204
        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
    ...
}
Copy after login

The above is the detailed content of What are the cross-domain solutions for SpringBoot projects?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template