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


前端: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("/**");
      }
    };
  }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM