如何解决前后端不同端口号 跨域问题

前端:Vue2.x 项目

后端:SpringBoot

报错:浏览器控制台报错403,Access to XMLHttpRequest at 'http://localhost:8080/xxx' from ...

1. 前端axios请求发送的默认端口要与后端的端口一致

let axiosInstance = axios.create({
  // 发送默认请求到本机的8280端口!!
  baseURL:'http://localhost:8280',
  timeout:3000
});

2. 后端Controller在类上面添加注解@CrossOrigin(origins = "*",maxAge = 3600)

@CrossOrigin(origins = "*",maxAge = 3600) //允许前后端跨域,响应前的缓存持续1小时
public class BankInfoController {
  // Your methods...
}

3. 在后端java包中新建一个包,里面新建一个类MyConfiguration,内容如下

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;
@SuppressWarnings("deprecation")
@Configuration
public class MyConfiguration {
  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
      }
    };
  }
}
上一篇:Spring Security OAuth2.0系列之密码模式


下一篇:Mybatis-Plus - 分页查询