Spring Boot 配置跨域

 用webstorm打开前端页面,报跨域了

 方式1:写个配置类

package com.blogspring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author: qiuj
 * @Description: 处理跨域
 * @Date: 2019/12/1 0001 9:38
 */
@Configuration
public class CORSConfig {

    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //  设置放行的地址
        corsConfiguration.addAllowedOrigin("http://localhost:63343");
        //  设置是否发送cookie 的信息
        corsConfiguration.setAllowCredentials(true);
        //  允许的请求头报文
        corsConfiguration.addAllowedHeader("*");
        //  允许的请求方法
        corsConfiguration.addAllowedMethod("*");
        //  设置映射路径
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        //  请求进来适用于所有的路由
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}

 方式2:在controller 类上或者方法上配置  @CrossOrigin

允许在特定处理程序类*和/或处理程序方法上进行跨域请求的注释。如果配置了适当的{@code HandlerMapping} *,则进行处理。

package com.blogspring.controller;

import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.blogspring.service.ICarouselService;

/**
 * @Author: qiuj
 * @Description:
 * @Date: 2019/12/1 0001 9:05
 */
@RestController
@RequestMapping("/index")
public class IndexController {

    @Autowired
    private ICarouselService iCarouselService;
    @CrossOrigin
    @GetMapping("/carousel")
    public R getCarousel(){
        return iCarouselService.getCarousel();
    }
}

posted @ 2019-12-01 10:17  邱健  阅读(60)  评论(0编辑  收藏  举报