一、概述
為啥需要跨域處理,通常我們的API一般是給到前端去調用,但是前端可能使用域名和沒提供的API域名是不一樣,這就引發了瀏覽器同源策略問題,所以我們需要做跨域請求支持。
FastAPI支持跨域的話,可以通過添加中間的形式,和bottle也有相似之處。不僅如此他還支持僅限於支持哪些域名進行跨域請求:
import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") async def main(): return {"message": "Hello World"} if __name__ == '__main__': uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True, debug=True)
二、演示跨域
環境說明:
前端:
操作系統:centos 7.6
ip地址:192.168.31.35
運行軟件:nginx
后端:
操作系統:windows 10
ip地址:192.168.31.61
運行軟件:pycharm
請求api
登錄到前端服務器,安裝nginx,並啟動。
yum install -y nginx
nginx
訪問默認頁面
http://192.168.31.35/
測試頁面
登錄到前端服務器,默認的nginx頁面目錄為:/usr/share/nginx/html
新建一個測試文件
cd /usr/share/nginx/html
vi test.html
內容如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <button id="api">請求接口</button> <h4>結果</h4> <div id="content"></div> <script> $('#api').click(function () { $.ajax({ //發送ajax請求 url: 'http://192.168.31.61:8000/', type: "get", data: {}, success: function (arg) { //arg = JSON.parse(arg); console.log(arg); $('#content').text(arg.message) //return false; }, error: function () { console.log("網絡請求錯誤!"); } }); }); </script> </body> </html>
訪問測試頁面
http://192.168.31.35/test.html
點擊請求接口按鈕,提示跨域。
為什么會出現跨域呢?因為同源策略。
同源策略是瀏覽器的一個安全功能,不同源的客戶端腳本在沒有明確授權的情況下,不能讀寫對方資源。所以192.168.31.35下的js腳本采用ajax讀取192.168.31.61里面的文件數據是會被拒絕的。
同源策略限制了從同一個源加載的文檔或腳本如何與來自另一個源的資源進行交互。這是一個用於隔離潛在惡意文件的重要安全機制。
三、解決跨域
一般解決跨域,是在后端完成的,設置允許跨域。
修改main.py,增加前端的url地址即可。

import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 前端頁面url origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost", "http://localhost:8080", "http://192.168.31.35", ] # 后台api允許跨域 app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") async def main(): return {"message": "Hello World"} if __name__ == '__main__': uvicorn.run(app='main:app', host="0.0.0.0", port=8000, reload=True, debug=True)
再次點擊按鈕,結果就會顯示出來了。
本文參考鏈接: