36. Springboot configures CORS to solve cross domain requests

Time:2020-11-29

CORS (cross origin resource sharing) “cross domain resource sharing” is a W3C standard. It allows the browser to send Ajax requests to cross domain servers, breaking the restriction that Ajax can only access resources in the site. CORS is used in many places. JS payment of wechat payment is to send cross domain request to wechat server through JS. Opening Ajax to access servers that can be accessed across domains greatly reduces the background development work, and the front-end and back-end work can also be well defined and divided. Let’s talk about how to make the spring boot project support CORS cross domain.

1. New project SC CORS, corresponding to pom.xml The documents are as follows

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>spring-cloud</groupId>
    <artifactId>sc-cors</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>sc-cors</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

2. Create a new configuration class to configure what conditions can be accessed across domains

package sc.cors.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("/cors/**")
        .allowedMethods("*")
        .allowedOrigins("*")
        .allowedHeaders("*");
    }
}

3. Create a new controller, including a resource that can be accessed across domains and a resource that cannot be accessed across domains

package sc.cors.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import sc.cors.model.User;

@RestController
public class CorsController {

    @RequestMapping("/cors/getUserInfo")
    public Map<String, Object> getUserInfo() {
        Map<String, Object> resp = new HashMap<String, Object>();
        resp.put("code", "success");
        resp.put("message", "success");
        User user = new User();
        user.setId(1);
        user.setPosition("cto");
        user.setUserName("huang jinjin");
        resp.put("body", user);
        return resp;
    }

    @RequestMapping("/nocors/listUserInfo")
    public Map<String, Object> listUserInfo() {
        Map<String, Object> resp = new HashMap<String, Object>();
        resp.put("code", "success");
        resp.put("message", "success");
        List<User> list = new ArrayList<User>();
        User user = new User();
        user.setId(1);
        user.setPosition("cto");
        user.setUserName("huang jinjin");
        list.add(user);
        resp.put("body", list);
        return resp;
    }

}

4. Other project files are shown in the figure below
36. Springboot configures CORS to solve cross domain requests

5. In the new project SC CORS web, the project is relatively simple and contains an important HTML file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>cors</title>
<script type="text/javascript"></script>
<script type="text/javascript">
    $(function(){
            $("#getUserInfo").click(function(){
                $.ajax({
                    url: "http://127.0.0.1:9088/cors/getUserInfo",
                    success: function(data){
                        console.log(data)
                        alert("getUserInfo");
                    }
                })
            });
    });

    $(function(){
        $("#listUserInfo").click(function(){
            $.ajax({
                url: "http://127.0.0.1:9088/nocors/listUserInfo",
                success: function(data){
                    console.log(data)
                    alert("listUserInfo");
                }
            })
        });
});

</script>
</head>
<body>
    < input type = "button" id = "getUserInfo" value = "CORS cross domain request getUserInfo" / > < br > < br / >
    < input type = "button" id = "listuserinfo" value = "CORS cross domain request listuserinfo" / >
</body>
</html>

remarks:

The port corresponding to SC CORS project is 9088  
  The port of SC CORS web project is 9087

6. Start the projects SC CORS and SC CORS web respectively
7. Verify cross domain requests
visit http://127.0.0.1 :9087/ index.html
36. Springboot configures CORS to solve cross domain requests
Click CORS cross domain request getUserInfo
36. Springboot configures CORS to solve cross domain requests
Click CORS cross domain request listuserinfo
36. Springboot configures CORS to solve cross domain requests