Home > Backend Development > Python Tutorial > How to Access My FastAPI Backend from a Different Machine on the Same Local Network?

How to Access My FastAPI Backend from a Different Machine on the Same Local Network?

DDD
Release: 2024-12-01 09:07:11
Original
474 people have browsed it

How to Access My FastAPI Backend from a Different Machine on the Same Local Network?

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

When running a FastAPI backend and a Next.js frontend on different machines on the same local network, accessing the backend from the frontend may encounter issues.

Setting the host flag to 0.0.0.0

To allow access from different machines, set the host flag to 0.0.0.0 in the uvicorn command:

uvicorn main:app --host 0.0.0.0 --port 8000
Copy after login

This allows the backend to listen on all IPv4 addresses of the local machine.

Adjusting Firewall Settings

Ensure that the Firewall allows external access to the specified port. Create an inbound firewall rule for Python, typically added automatically when Python is allowed to communicate through the Firewall.

Adjusting CORS Settings

Configure CORS middleware to enable cross-origin requests:

origins = ['http://localhost:3000','http://192.168.178.23:3000']

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

Making HTTP requests in JavaScript

In JavaScript fetch requests, use the same domain name as entered in the browser's address bar, along with the backend's port number:

fetch('http://192.168.178.23:8000/people', {...
Copy after login

When testing locally on the same machine, use fetch with the correct domain name (e.g., http://127.0.0.1:8000/people) or relative paths (e.g., '/people') when both frontend and backend run on the same port and IP. If the frontend's origin differs from the backend's, add it to the CORS settings.

The above is the detailed content of How to Access My FastAPI Backend from a Different Machine on the Same Local Network?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template