We usually use FastApi as an interface, and since it is an interface service, cross-domain parameter transfer is an inevitable problem.

Our Api service is 127.0.0.0:8000, and our main domain name is 127.0.0.1,

Different ports belong to different domains. The following description also applies to other cross-domain scenarios, such as the main site is www.xx.com and the domain name of the API service is api.xx.com.

Now the site is calling the API interface, let’s use jquery ajax to try:

Create a test file, zhiliao.html, write the following and access it:

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script> // Import CDN jquery
$.get("http://127.0.0.1:8000/".function(data){ / / get data
console.log(data);// Console prints data
});
</script>
Copy the code

As you can see, the access failed because the domain is different:

Add a few lines of code and end up like this:

# -*- coding:utf-8 -*-

from fastapi import FastAPI 
from starlette.middleware.cors import CORSMiddleware  # Introduce the CORS middleware module

Create a FastApi instance
app = FastAPI()

Set the domain name to allow access
origins = ["http://127.0.0.1"]  # can also be set to "*", which is all.

Set cross-domain parameter transfer
app.add_middleware(
    CORSMiddleware, 
    allow_origins=origins,  # set permitted origins
    allow_credentials=True,
    allow_methods=["*"].Set HTTP methods that are allowed to cross domains, such as GET, POST, PUT, etc.
    allow_headers=["*"])  Allows cross-domain headers, can be used to identify sources, etc.

The following function is used to handle "/" GET requests
@app.get("/")
def read_root(a):
    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 }
Copy the code

We refresh the browser:

Succeeded in transferring parameters across domains and obtaining data. Procedure

Welcome to my blog: LookCos blog