SpringBoot后台解决前端跨域问题

 前端跨域问题,在springboot项目中加入配置文件CorsConfig.java,重启后可以解决跨域问题

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;

@Configuration
public class CorsConfig {

    // 当前跨域请求最大有效时长。这里默认1天
    private static final long MAX_AGE = 24 * 60 * 60;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}

在使用Spring Boot和Vue开发前后端分离的项目中,解决跨域问题可以采用以下两种方法: 1. 在前端Vue中解决跨域问题:可以通过在Vue项目中配置代理来解决跨域。具体做法是在Vue项目的配置文件(一般是vue.config.js)中添加proxy配置,将需要跨域访问的后端接口地址映射到当前的开发环境,示例代码如下: ```javascript module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', // 后端接口地址 changeOrigin: true, // 是否允许跨域 pathRewrite: { '^/api': '' // 路径重写,将请求路径中的'/api'去掉 } } } } } ``` 这样,在发送请求时,只需将路径前缀设置为'/api'即可,比如发送登录请求可以写成`this.$axios.post('/api/login')`。 2. 在后台Spring Boot解决跨域问题:可以通过在Spring Boot项目中添加跨域配置来解决跨域。具体做法是在后台的配置类或配置文件中添加允许跨域请求的配置,示例代码如下: ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许所有请求跨域访问 .allowedOrigins("*") // 允许所有域名进行跨域访问 .allowedMethods("*") // 允许所有请求方法进行跨域访问 .allowedHeaders("*") // 允许所有请求头进行跨域访问 .allowCredentials(true); // 允许携带cookie进行跨域访问 } } ``` 这样,后台接收到前端的跨域请求时就会进行相应的处理,从而解决跨域问题。 总结来说,解决Spring Boot和Vue跨域问题的方法有两种:在前端Vue中配置代理实现跨域,或在后台Spring Boot中添加跨域配置实现跨域。具体选择哪种方法取决于你的项目需求和开发习惯。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot与Vue交互解决跨域问题【亲测已解决】](https://blog.csdn.net/weixin_44985880/article/details/120620207)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值