前端Vue 后端FastApi 跨域 CORS

前端跨域方法和后端跨域方法二选一,推荐后端跨域

什么是跨域问题?

前端是localhost:3000,后端是localhost:8000 ,就是跨域了

Vue跨域方法 

在vue.config.ts中,server中,增加proxy部分的代码,意思是 将/api 重写成 后端的地址

  server: {

    host:'0.0.0.0',
    open: true,
    proxy: {
      '/api': {
        target: "http://127.0.0.1:8000",
        changeOrigin: true,
        rewrite(path) {
          return path.replace(/^\/api/, '')
        },
      },
      

      },
  },

然后vue中用axios访问后端的网址就写成

import axios from 'axios'
export const addNutInfo = (req:any) => {
    return axios.post('/api/nut/${line}',req)}

相当于 http://127.0.0.1:8000/nut/${line} 

 

后端FastAPI跨域方法

参考https://fastapi.tiangolo.com/zh/tutorial/cors/

origins列表中写的是 前端端口号 比如3000

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"}

推荐后端跨域的办法,vue前端直接写后端端口就行

export const getNutSum=(line:any) =>{
    return axios.get(`http://127.0.0.1:8000/getsum/${line}`)
}

 

 

相关推荐

  1. Fastapi+Jsonp实现前后请求

    2024-05-09 13:58:07       32 阅读
  2. ASP.NET Core WebAPI_解决问题(前端)

    2024-05-09 13:58:07       31 阅读
  3. Vue前后链接

    2024-05-09 13:58:07       38 阅读
  4. 解决前端问题,解决方法

    2024-05-09 13:58:07       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-09 13:58:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-09 13:58:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-09 13:58:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-09 13:58:07       18 阅读

热门阅读

  1. 跨域问题解决方案

    2024-05-09 13:58:07       8 阅读
  2. wifi执法记录仪移植出现的问题

    2024-05-09 13:58:07       11 阅读
  3. 邮件服务器有什么作用?

    2024-05-09 13:58:07       9 阅读
  4. Tengine安装及负载均衡(带check实现)

    2024-05-09 13:58:07       12 阅读
  5. QT作业3

    QT作业3

    2024-05-09 13:58:07      10 阅读
  6. DAY 3

    DAY 3

    2024-05-09 13:58:07      9 阅读
  7. Spring 框架中用到的设计模式

    2024-05-09 13:58:07       11 阅读
  8. Vue3+Element+TS动态菜单+按钮权限控制实现探索

    2024-05-09 13:58:07       9 阅读
  9. vue从登陆注册开始

    2024-05-09 13:58:07       13 阅读
  10. 前端造轮子神器 —— Hooks

    2024-05-09 13:58:07       12 阅读
  11. C++基础-编程练习题和答案

    2024-05-09 13:58:07       13 阅读
  12. 不可逆加密算法、可逆加密算法

    2024-05-09 13:58:07       9 阅读