OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

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

  • Thread starter Thread starter Fede Camara Halac
  • Start date Start date
F

Fede Camara Halac

Guest
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:

Code:
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:

Code:
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

Code:
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:

Code:
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:

Code:
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=["*"],
)
<p>Both the FastAPI backend and the Next.js frontend are running on <code>localost</code>. On the same computer, the frontend makes API calls using <code>fetch</code> without any issues. However, on a different computer on the <strong>same</strong> network, e.g., on <code>192.168.x.x</code>, the frontend runs, but its API calls are no longer working.</p>
<p>I have tried using a proxy as next.js but that still does not work.</p>
<p>Frontend:</p>
<pre class="lang-js prettyprint-override"><code>
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>)}
</>
)
}
</code></pre>
<p>The Next.js app loads the <code>env.local</code> file at startup, which contains:
<code>NEXT_PUBLIC_API=http://locahost:20002</code></p>
<p>Backend:</p>
<pre class="lang-py prettyprint-override"><code>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
</code></pre>
<p>The frontend runs with: <code>npm run dev</code>, and outputs</p>
<pre><code>ready - started server on 0.0.0.0:3000, url: http://localhost:3000
</code></pre>
<p>The backend runs with: <code>uvicorn hogar_api.main:app --port=20002 --host=0.0.0.0 --reload</code>, and outputs:</p>
<pre><code>INFO: Uvicorn running on http://0.0.0.0:20002 (Press CTRL+C to quit)
</code></pre>
<p>When I open the browser on <code>http://localhost:3000</code> <em>on the same machine</em> the list of <code>Person</code> is displayed on the screen.</p>
<p>When I open the browser on <code>http://192.168.x.x:3000</code> <em>on another machine on the <em>same</em> network</em>, I get the "Failed to Load..." message.</p>
<p>When I open the FastAPI swagger docs on either machine, the documentation is displayed correctly and all the endpoints work as expected.</p>
<p>CORS look like this:</p>
<pre class="lang-py prettyprint-override"><code>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=["*"],
)
</code></pre>
 

Latest posts

Top