[Python] How to access FastAPI backend from a different machine/IP on the same local network?

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    Both the FastAPI backend and the Next.js frontend are running on localost. On the same computer, the frontend makes API calls using fetch without any issues. However, on a different computer on the same network, e.g., on 192.168.x.x, the frontend runs, but its API calls are no longer working.

    I have tried using a proxy as next.js but that still does not work.

    Frontend:


    export default function People({setPerson}:peopleProps) {
    const fetcher = async (url:string) => await axios.get(url).then((res) => res.data);
    const { data, error, isLoading } = useSWR(`${process.env.NEXT_PUBLIC_API}/people`, fetcher);
    if (error) return <div>"Failed to load..."</div>;
    return (
    <>
    {isLoading? "Loading..." :data.map((person: Person) =>
    <div key={person.id}> {person.name} </div>)}
    </>
    )
    }


    The Next.js app loads the env.local file at startup, which contains: NEXT_PUBLIC_API=http://locahost:20002

    Backend:

    rom typing import List
    from fastapi import APIRouter, Depends
    from ..utils.db import get_session as db
    from sqlmodel import Session, select
    from ..schemas.person import Person, PersonRead
    router = APIRouter()

    @router.get("/people", response_model = List[PersonRead])
    async def get_people(sess: Session = Depends(db)):
    res = sess.exec(select(Person)).all()
    return res


    The frontend runs with: npm run dev, and outputs

    ready - started server on 0.0.0.0:3000, url: http://localhost:3000


    The backend runs with: uvicorn hogar_api.main:app --port=20002 --host=0.0.0.0 --reload, and outputs:

    INFO: Uvicorn running on http://0.0.0.0:20002 (Press CTRL+C to quit)


    When I open the browser on http://localhost:3000 on the same machine the list of Person is displayed on the screen.

    When I open the browser on http://192.168.x.x:3000 on another machine on the same network, I get the "Failed to Load..." message.

    When I open the FastAPI swagger docs on either machine, the documentation is displayed correctly and all the endpoints work as expected.

    CORS look like this:

    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware

    app = FastAPI()

    origins = [
    "http://localhost:3000",
    ]

    app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    )

    Continue reading...

Compartilhe esta Página