赞
踩
前端跨域方法和后端跨域方法二选一,推荐后端跨域
前端是localhost:3000,后端是localhost:8000 ,就是跨域了
在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}
参考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}`)
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。