解决跨域问题(springboot)

前后端分离项目,前后端端口肯定会设置不同的端口,那么就需要解决跨域问题

在项目里面创建一个config包,CorsConfig类,前端无需配置跨域,然后重启springboot和npm,即可解决跨域问题,实现跨域访问

(前端端口8080,后端端口9090)corsConfiguration.addAllowedOrigin("http://localhost:8080");

引号里面的内容跟随自己的前端端口号的改变而改变

package com.zhang.springboot.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;
 
@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("http://localhost:8080"); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.setMaxAge(MAX_AGE);
        source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
 
 
}

参考文章:

This subject is anonymous - it does not have any identifying principals and authorization operations_烤鸭的世界我们不懂的博客-CSDN博客

关于shiro授权 This subject is anonymous - it does not have any identifying principals and_心动的偏执的博客-CSDN博客

你可能感兴趣的:(spring,boot,前端,javascript)