如何解決前后端不同端口號 跨域問題


前端: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