springboot2.0 对CORS的支持

本文介绍了一种在Spring Boot项目中通过自定义配置类实现跨域资源共享(CORS)的方法。该配置允许特定来源(如http://localhost:9999)对指定API路径(/api/**)进行跨域访问,同时对于同一域名下的请求则不受限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先自定义一个配置类

package com.springboot2.thyemleaf.Configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * Created by  lpw'ASUS on 2018/5/29.
 * 自定义CORS配置类
 */
@Configuration
public class CustomCorsConfiguration {

    @Bean
    public WebMvcConfigurer getConfigure(){
       return new WebMvcConfigurerAdapter() {
           @Override
           public void addCorsMappings(CorsRegistry registry) {
              //允许访问哪个接口,允许站外的http://localhost:8989访问,allowedOrigins这里天的地址是将来要请求你的地址,例如baidu要请求你,就写百度
              registry.addMapping("/api/**").allowedOrigins("http://localhost:9999");
           }
       };
    }

}

以项目本身端口访问不收限制。例如本服务为localhost:8888、那么以localhost:8888开头的请求路径不受限制Controller,除此之外,http://localhost:9999 只能登陆一部分人。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值