關於java後端跨域請求的解決方案!!!!終極簡單實用版

那什麼是跨域請求??我們又什麼時候需要用到跨域請求呢???

什麼是跨域請求

跨域請求是來自於瀏覽器的同源機制,凡是發送請求url的協議、域名、端口三者之間任意一與當前頁面地址不同即爲跨域。在通信不被允許的時候,我們就需要使用跨域請求啦!!!具體可以查看下錶。
在這裏插入圖片描述

解決方案

新建java類 名爲CorsConfig 代碼如下

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允許任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        // 允許任何頭
        corsConfiguration.addAllowedHeader("*");
        // 允許任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 對接口配置跨域設置
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

這裏只需要對域名、頭、使用方法設置“*”,即全部允許就可以了。
下面給大家解釋一下 上面所用到的註解
@Configuration標註在類上,相當於把該類作爲spring的xml配置文件中的,作用爲:配置spring容器(應用上下文)
相當於

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>

@Bean標註在方法上(返回某個實例的方法),等價於spring的xml配置文件中的,作用爲:註冊bean對象

以上就是跨域請求終極簡單版解決方案!!!還有很多做法的,大家自己研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章