天天看點

前後端分離架構跨域問題的解決辦法-java和python做後端的實作

跨域-它是浏覽器最重要的一項安全政策即同源政策造成的.

所謂同源是指,域名,協定,端口均相同:

http://www.baidu.com/index.html 調用 http://www.baidu.com/server (非跨域)

http://www.baidu.com/index.html 調用 http://www.baidu222.com/server(主域名不同:baidu/baidu222,跨域)

http://image.baidu.com/index.html 調用 http://video.baidu.com/server(子域名不同:image/video,跨域)

http://www.baidu.com:8081/index.html 調用 http://www.baidu.com:8082/server(端口不同:8080/8081,跨域)

http://www.baidu.com/index.html 調用 https://www.baidu.com/server(協定不同:http/https,跨域)

另外要注意:127.0.0.1/localhost也屬于跨域行為。

當浏覽器執行前端頁面的js腳本時,就會檢查腳本所屬于頁面是否同源,如果不同源,請求就會失敗。

------------------------------------------------- 分割線---------------------------------------------------------------------------------------

java後端實作跨域:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

   /*     config.setAllowCredentials(true); // 允許cookies跨域
        config.addAllowedOrigin("*");// #允許向該伺服器送出請求的URI,*表示全部允許,在SpringMVC中,如果設成*,會自動轉成目前請求頭中的Origin
        config.addAllowedHeader("*");// #允許通路的頭資訊,*表示全部
        config.setMaxAge(18000L);// 預檢請求的緩存時間(秒),即在這個時間段裡,對于相同的跨域請求不會再預檢了
        config.addAllowedMethod("OPTIONS");// 允許送出請求的方法類型,*表示全部允許
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");*/
        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source =
                new org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}
      

------------------------------------------------- 分割線---------------------------------------------------------------------------------------

後端python+fastApi+uvicorn的實作跨域:

from fastapi import FastAPI

import uvicorn

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [

    "http://www.baidu.com",

    "http://image.baidu.com:8888",

    "http://vedio.baidu.com:8888"

    "http://vedio.baidu.com:5555"

]

app.add_middleware(

    CORSMiddleware,

    # CORS_ORIGIN_ALLOW_ALL=True,

    allow_origins=origins,

    allow_credentials=True,

    allow_methods=["*"],

    allow_headers=["*"]

)

------------------------------------------------- 分割線---------------------------------------------------------------------------------------

前端VUE的實作:

 methods: {

            PostQuery: function () {

                this.$axios.post(this.getUrl()).then(response => {

                    var jsonData;

                    if (response) {

                        this.$Message.error('查詢結果正确傳回')

                    } else {

                        this.showTable = false;

                        this.$Message.error('查詢接口未傳回任何結果')

                    }

                }).catch(ex => {

                    this.$Message.error('查詢接口異常請聯系程式員小哥');

                    console.log("異常資訊:" + ex.toLocaleString());

                })

            },

            getUrl: function () {

                return 'http://www.baidu.com.com/query';

            }

        },