跨域问题解决

跨域

举例A网站部署在 localhost:63343 请求 loocalhost:8080/api/user/add,就会出现跨域问题。


同源策略

同源策略:协议主机端口,只有这三者全部相同时,才可以相互访问。

现在接口地址为https://127.0.0.1:8080,请判断以下哪些可以通过:

访问地址 描述 结果
https://127.0.0.1:8080/api/mall/list 协议、主机、端口都相同 通过
https://127.0.0.1:8081 端口不同 不通过
https://127.0.0.2:8080 主机不同 不通过
http://127.0.0.1:8080 协议不同 不通过

跨域问题解决

CORS解决跨域

CORS背后的基本思想是使用自定义的HTTP头部允许浏览器和服务器相互了解对方,从而决定请求或响应成功与否。

Access-Control-Allow-Origin: 指定授权访问的域
Access-Control-Allow-Methods:授权请求的方法(GET, POST, PUT, DELETE,OPTIONS等)

Spring 配置:

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        // 允许的前端域
        config.addAllowedOrigin("*");
        // 其他跨域配置,例如允许的方法、头部等
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");

        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

举例

前端HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>test</title>
    <meta charset="utf-8">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

<body>

<label for="username">姓名:</label><input id="username" placeholder="请输入姓名"></input>
<label for="sex">性别:</label><input id="sex" placeholder="请输入性别"></input>
<button onclick="addUser()">添加用户</button>

</body>
<script>
    function addUser() {
        const username = document.getElementById("username").value;
        const sex = document.getElementById("sex").value;

        axios({
            method: 'post',
            url: "http://localhost:8080/user/add",
            data: {
                username: username,
                sex: sex
            }
        }).then(function (response) {
            console.log(response.data)
        }).catch(function (error) {
            console.error("错误", error);
        });
    }

</script>
</html>

SpringBoot 后端文件:

@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/add")
    public String hello(@RequestBody UserInfoDto userInfoDto) {
        System.out.println(userInfoDto);
        return "Hello, User!";
    }
    
}


@Data
public class UserInfoDto {
    private String username;
    private String sex;
}


@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        // 允许的前端域
        config.addAllowedOrigin("*");
        // 其他跨域配置,例如允许的方法、头部等
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");

        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

posted @ 2024-02-18 21:49  帅气的涛啊  阅读(7)  评论(0编辑  收藏  举报