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.
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
This allows the backend to listen on all IPv4 addresses of the local machine.
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.
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=["*"], )
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', {...
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!