第6步 跨域请求

什么是跨越

现在前后端分离的模式决定了前端代码或者浏览器需求请求不同来源的数据,因此我们在项目中开启 跨域请求。这样可以让不同的客户端调用我们的接口程序。

SpringBoot解决跨越问题

我们实现 WebMvcConfiguration 接口即可 我们编写自己的类 CorsConfig 实现 WebMvcConfiguration 接口

package com.bitgeek.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("/**")	// 允许跨域访问的路径
        .allowedOrigins("*")	// 允许跨域访问的源
        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")	// 允许请求方法
        .maxAge(168000)	// 预检间隔时间
        .allowedHeaders("*")  // 允许头部设置
        .allowCredentials(true);	// 是否发送cookie
    }
}
Last Updated 9/22/2025, 10:01:26 PM