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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值