springboot如何解决跨域问题?

html 代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="http://localhost:8000/library/jquery/3.6.0/jquery.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
            $.get("http://localhost:8080/user")
        </script>
    </body>
</html>

配置类, 跨域方案是参考百度上的

package com.abc.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 WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("token")
                .maxAge(3600);
    }

}

控制器

package com.abc.controller;

import com.abc.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping("/user")
    public String getUser() {
        return new User("adm", "123").toString();
    }

}

跨域请求
前台报错
image.png

后台
Request processing failed; nested exception is java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.

阅读 2.5k
3 个回答

这个设置成false
.allowCredentials(false) 后台日志已经告诉你了,你静下来心读一下就行

public class CorsInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
    String origin = request.getHeader("Origin");
    response.setHeader("Access-Control-Allow-Origin", origin);
    response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT");
    response.setHeader("Access-Control-Allow-Headers", "Accept,Accept-Language,Content-Language,Last-Event-ID,Content-Type");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setContentType("application/json; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    return !HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod());
}

}

将这个CorsInterceptor 注册到

@Override
public void addInterceptors(InterceptorRegistry registry) {
    // 跨域拦截器
    registry.addInterceptor(corsInterceptor)
            .addPathPatterns("/**");

}

针对以前遇到的问题补充: 新版本的 SpringBoot 这样写会报错
如果是新版本, 将 allowedOrigins 方法替换成 allowedOriginPatterns 即可

package com.raxly.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 RaxlyWebMvcConfigurer implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("token")
                .maxAge(3600);
    }

}
推荐问题