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.
原因
當(dāng)前端請求的端口和后端接受請求的端口不一致
解決
創(chuàng)建一個配置文件CorConfig.java,允許任何的請求頭、請求方法訪問。
此處是放開后端,允許前端訪問,只需要設(shè)置訪問源地址即可
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 { // 當(dāng)前跨域請求最大有效時(shí)長。這里默認(rèn)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 設(shè)置訪問源地址(允許這個網(wǎng)站訪問后臺) corsConfiguration.addAllowedHeader("*"); // 2 設(shè)置訪問源請求頭 corsConfiguration.addAllowedMethod("*"); // 3 設(shè)置訪問源請求方法 corsConfiguration.setMaxAge(MAX_AGE); source.registerCorsConfiguration("/**", corsConfiguration); // 4 對接口配置跨域設(shè)置 return new CorsFilter(source); } }
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于File與MultipartFile的用法概述
這篇文章主要介紹了關(guān)于File與MultipartFile的用法概述,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09SpringBoot解析LocalDateTime失敗:Uniapp傳輸時(shí)間變1970的原因與解決方案
這篇文章主要介紹了SpringBoot解析LocalDateTime失???Uniapp傳輸時(shí)間變1970的原因與解決方案,文中通過代碼示例給大家講解的非常詳細(xì),需要的朋友可以參考下2025-03-03Java object wait notify notifyAll代碼解析
這篇文章主要介紹了Java object wait notify notifyAll代碼解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11springboot集成開發(fā)實(shí)現(xiàn)商場秒殺功能
這篇文章主要介紹了springboot集成實(shí)現(xiàn)商品秒殺功能,秒殺系統(tǒng)業(yè)務(wù)流程,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12