3.8SpringBoot之跨域问题

3.8SpringBoot之跨域问题,第1张

新建项目cros01,web依赖

package com.example.cors01;

import org.springframework.web.bind.annotation.*;

@RestController
//@CrossOrigin(origins = "http://localhost:8081")
//maxAge: 设置以秒为单位的缓存时间
//origins: 设置允许跨域的域名,可以设置多个
//allowCredentials: 设置是否允许发送Cookie
//allowedHeaders: 设置允许跨域的Header
//exposedHeaders: 设置跨域时允许返回的Header
//methods: 设置允许跨域的请求方法


public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello cros";
    }


    @PostMapping("/hello")
    public String helloPost(){
        return "hello cros";
    }
}

新建项目cros02

01.html




    
    
    Title






将cros2的运行端口变成8081

运行之后:点击get按钮,出现错误,跨域问题

 解决跨域问题有3种方法

1.在方法或者类上面加注解@CrossOrigin

package com.example.cors01;

import org.springframework.web.bind.annotation.*;
@RestController
@CrossOrigin(origins = "http://localhost:8081")

//maxAge: 设置以秒为单位的缓存时间
//origins: 设置允许跨域的域名,可以设置多个
//allowCredentials: 设置是否允许发送Cookie
//allowedHeaders: 设置允许跨域的Header
//exposedHeaders: 设置跨域时允许返回的Header
//methods: 设置允许跨域的请求方法


public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello cros";
    }


    @PostMapping("/hello")
    public String helloPost(){
        return "hello cros";
    }
}

2.实现WebMvcConfigurer

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("http://localhost:8081")
                .maxAge(1800);
    }
}

3.注入一个CorsFilter到容器



@Configuration
public class WebMvcConfig  {


@Bean

    CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration buildConfig = new CorsConfiguration();
        buildConfig.addAllowedOrigin("http://localhost:8081");
        buildConfig.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", buildConfig);
        return new CorsFilter(source);
    }

}

 

第一个是针对某一个方法或者类,而下面两个是针对全局

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/871961.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-13
下一篇2022-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存