陈程的技术博客

  • 关于作者
全栈软件工程师
一个专注于技术研究创新的程序员
  1. 首页
  2. linux
  3. 正文

记一次fastapi做后台的跨域问题

2021年9月6日 1417点热度 0人点赞 0条评论

现在用python的fastapi做了一个后台部署在服务器上,前端采用的vue-ant-admin,直接调用fastapi一直出错

 

发现是跨域问题,按照网上查询的fastapi做跨域配置:

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)

 

这个方法没用,还是有跨域问题!!!!

没办法 ,只能通过nginx转发接口,把允许跨域的配置配在了nginx配置中

 

 
server {
         listen       6013;
         
         location / {
             proxy_pass http://127.0.0.1:6012/;
             add_header 'Access-Control-Allow-Origin' '*';
             add_header 'Access-Control-Allow-Credentials' 'true';
             add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
             add_header 'Access-Control-Allow-Headers' 'DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type';
         }
     }

如果遇到这个问题:

[emerg] bind() to 0.0.0.0:8380 failed (13: Permission denied)

首先,查看http允许访问的端口:

semanage port -l | grep http_port_t
http_port_t tcp 80, 81, 443, 488, 8008, 8009, 8443, 9000

其次,将要启动的端口加入到如上端口列表中

emanage port -a -t http_port_t -p tcp 8090
标签: fastapi nginx python
最后更新:2021年9月6日

博主

全栈工程师,侧重项目技术解决方案规划和开发

打赏 点赞
< 上一篇
下一篇 >

文章评论

取消回复

分类
  • .NET (65)
  • docker (3)
  • linux (12)
  • python (20)
  • web (14)
  • 小程序 (4)
  • 数据库 (2)
  • 未分类 (4)
  • 杂七杂八 (10)
标签聚合
linux DevExpress python centos nginx winform C# js
最新 热点 随机
最新 热点 随机
.NET开发手册标准参考 招募兼职前端开发 Centos安装dotnet6环境 VS上切换分支,vs编译运行出现bug,A fatal error was encountered彻底解决方案 用C#封装一个线程安全的缓存器,达到目标定时定量更新入库 C#通过特性的方式去校验指定数据是否为空
一个对缓存操作的类DataCache winform 微秒级别的定时器 centOS常用操作命令 用C#写一个AI智能回答机器人 用ASP.NET写一个简单的WebAPI .NET开发手册标准参考

COPYRIGHT © 2021 陈程的技术博客. ALL RIGHTS RESERVED.

THEME KRATOS MADE BY VTROIS