我们通常会拿FastApi来做接口,既然是接口服务,那么跨域传参是必然要碰到的问题。
现有情景如下我们的Api服务是127.0.0.0:8000,而我们的网站主域名是127.0.0.1,
不同端口属于不同域,下面的介绍也适合其他跨域场景比如主站是www.xx.com而api服务的域名是api.xx.com,同样适合。
现在网站要调用api的接口,我们用jquery的 ajax试一下:
建立一个测试文件zhiliao.html
,写入如下内容并访问:
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> //引入CDN jquery
$.get("http://127.0.0.1:8000/", function(data){ //get数据
console.log(data);//控制台打印数据
});
</script>
可以看到,由于是不同域,访问失败:
加上几行代码,最终如下:
# -*- coding:utf-8 -*-
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware #引入 CORS中间件模块
#创建一个FastApi实例
app = FastAPI()
#设置允许访问的域名
origins = ["http://127.0.0.1"] #也可以设置为"*",即为所有。
#设置跨域传参
app.add_middleware(
CORSMiddleware,
allow_origins=origins, #设置允许的origins来源
allow_credentials=True,
allow_methods=["*"], # 设置允许跨域的http方法,比如 get、post、put等。
allow_headers=["*"]) #允许跨域的headers,可以用来鉴别来源等作用。
#创建访问路径,下面的函数用来处理"/"的GET请求
@app.get("/")
def read_root():
return {"Hello": "Api"}
@app.get("/hello/{name}")
def hello(name):
res = {}
res['name'] = name
return res
@app.get("/zhiliao")
def read_args(name:str, age:int):
return {"name": name, "age":age }
我们刷新浏览器:
跨域传参成功,获取数据成功。
欢迎访问我的博客:LookCos的博客