CORS实现跨域请求

CORS跨域请求配置类

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

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //addAllowedOrigin:设置访问源地址
        corsConfiguration.addAllowedOrigin("*");
        //addAllowedHeader:设置访问源请求头
        corsConfiguration.addAllowedHeader("*");
        //addAllowedMethod:设置访问源请求方法
        corsConfiguration.addAllowedMethod("*");
        //GET:请求指定的页面信息,并返回实体主体
        /*corsConfiguration.addAllowedMethod(HttpMethod.GET);*/
        //HEAD:类似于GET请求,只不过返回的响应中没有具体的内容,用于获取报头
        /*corsConfiguration.addAllowedMethod(HttpMethod.HEAD);*/
        //POST:向指定资源提交数据进行处理请求,数据被包含在请求体中
        /*corsConfiguration.addAllowedMethod(HttpMethod.POST);*/
        //PUT:从客户端向服务器端传送的数据取代指定的文档内容
        /*corsConfiguration.addAllowedMethod(HttpMethod.PUT);*/
        //PATCH:用于对资源进行部分修改
        /*corsConfiguration.addAllowedMethod(HttpMethod.PATCH);*/
        //DELETE:请求服务器删除指定页面
        /*corsConfiguration.addAllowedMethod(HttpMethod.DELETE);*/
        //OPTIONS:允许客户端查看服务器的性能
        /*corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);*/
        //TRACE:回显服务器收到的请求,主要用于测试或诊断
        /*corsConfiguration.addAllowedMethod(HttpMethod.TRACE);*/
        //setMaxAge:设置跨域请求最大有效时长,单位:秒
        corsConfiguration.setMaxAge(3600L);
        //setAllowCredentials:是否支持Cookie
        corsConfiguration.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值