资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

SpringBoot中怎么解决跨域请求问题

今天就跟大家聊聊有关Spring Boot 中怎么解决跨域请求问题,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

创新互联主要从事成都网站设计、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务宝兴,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792

解决方法

跨域问题可以在前端解决也可以在后端解决,我个人觉得在后端解决更方便一些。

只需要添加一个配置类。

package com.example.demo.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("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

在本项目中,我的源码放在com.example.demo包下,在这个包中新建一个包,放入该配置类,即可解决跨域问题。

注意allowedOriginPatterns()方法不要用allowedOrigins(),不然项目运行时请求后端接口会报错。

org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method 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.

看完上述内容,你们对Spring Boot 中怎么解决跨域请求问题有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


网页题目:SpringBoot中怎么解决跨域请求问题
本文网址:http://cdkjz.cn/article/pohdig.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220