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

