前端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}`)
}

 

 


文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。

发表评论

快捷回复:表情:
评论列表 (暂无评论,0人围观)

还没有评论,来说两句吧...

目录[+]

取消
微信二维码
微信二维码
支付宝二维码