章工运维 章工运维
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)

章工运维

业精于勤,荒于嬉
首页
  • linux
  • windows
  • 中间件
  • 监控
  • 网络
  • 存储
  • 安全
  • 防火墙
  • 数据库
  • 系统
  • docker
  • 运维工具
  • other
  • elk
  • K8S
  • ansible
  • Jenkins
  • GitLabCI_CD
  • 随笔
  • 面试
  • 工具
  • 收藏夹
  • Shell
  • python
  • golang
友链
  • 索引

    • 分类
    • 标签
    • 归档
    • 首页 (opens new window)
    • 关于我 (opens new window)
    • 图床 (opens new window)
    • 评论 (opens new window)
    • 导航栏 (opens new window)
周刊
GitHub (opens new window)
  • python

    • python基础

    • FastAPI

      • FastAPI-快速入门1
      • FastAPI-路由2
      • FastApi-参数提交3
      • FastApi-响应报文
      • FastApi-错误处理
      • FastApi-中间件
      • FastApi-跨域处理
        • 二、演示跨域
        • 环境说明:
          • 前端:
          • 后端:
        • 请求api
        • 测试页面
      • 依赖注入之Depends
    • python每日练习脚本

    • python3给防火墙添加放行
    • python生成部署脚本
    • python将多个文件内容输出到一个文件中
    • 使用 Aligo 定时备份服务器文件
    • python监控日志文件并发送钉钉告警
    • python监控数据库脚本并发送钉钉告警
    • 使用python编写自动化发布脚本
    • 查询redis列表某个元素
    • centos7安装python3
    • python环境管理工具介绍
    • conda安装和镜像源配置
    • pip更换国内源
    • python爬虫
    • python环境启动服务报错缺少glibc库版本
    • 监控目录或文件变化
    • 批量更改文件
    • python引用数据库
  • shell

  • go

  • 编程
  • python
  • FastAPI
章工运维
2024-12-04
目录

FastApi-跨域处理

# 一、概述

为啥需要跨域处理,通常我们的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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 二、演示跨域

# 环境说明:

# 前端:

操作系统: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>
<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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

访问测试页面

http://192.168.31.35/test.html

点击请求接口按钮,提示跨域。

c43922049fe46f66.png

为什么会出现跨域呢?因为同源策略。

同源策略是浏览器的一个安全功能,不同源的客户端脚本在没有明确授权的情况下,不能读写对方资源。所以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)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

再次点击按钮,结果就会显示出来了。

dbc17b4db2839c12.png

原文链接 (opens new window)

微信 支付宝
上次更新: 2024/12/13, 12:36:19

← FastApi-中间件 依赖注入之Depends→

最近更新
01
shell脚本模块集合
05-13
02
生活小技巧(认知版)
04-29
03
生活小技巧(防骗版)
04-29
更多文章>
Theme by Vdoing | Copyright © 2019-2025 | 点击查看十年之约 | 鄂ICP备2024072800号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式