Springboot如何解決前端請求跨域的問題
Springboot解決前端請求跨域
Access to fetch at from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
原因
當前端請求的端口和后端接受請求的端口不一致
解決
創(chuàng)建一個配置文件CorConfig.java,允許任何的請求頭、請求方法訪問。
此處是放開后端,允許前端訪問,只需要設置訪問源地址即可
package com.zhang.demo.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); } }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot解析LocalDateTime失敗:Uniapp傳輸時間變1970的原因與解決方案
這篇文章主要介紹了SpringBoot解析LocalDateTime失?。縐niapp傳輸時間變1970的原因與解決方案,文中通過代碼示例給大家講解的非常詳細,需要的朋友可以參考下2025-03-03Java object wait notify notifyAll代碼解析
這篇文章主要介紹了Java object wait notify notifyAll代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11