1

While trying to fetch a simple api made using FastAPI with Reactjs in the frontend, I keep getting no response:

Here's the FastAPI code:

@app.get("/haha")
async def read_haha():
    return "haha"

Postman's test on the api :

enter image description here

And lastly reactjs code :

import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import 'bootstrap/dist/css/bootstrap.min.css'
import Button from 'react-bootstrap/Button';


function App() {
    const [response, setResponse] = useState('');
    useEffect(() => {
        fetch('http://127.0.0.1:8000/haha')
        .then(res => res.text())
        .then(data => {
            console.log(data); // add this line to see the data returned by the API
            setResponse(data);
        })
        .catch(error => console.error(error));
     }, []);

    return (
        <div>
        <h1>API Response:</h1>
        <p>{response}</p>
        </div>
    );
}

export default App;

The result of all of this :

enter image description here

Since I am new to FastAPI and React maybe the issue is obvious to everyone, but in my case I spent hours without finding a solution to it...

Chris
  • 18,724
  • 6
  • 46
  • 80
jolaxbeat
  • 41
  • 3
  • does `console.log(data)` show something? – Victor Santizo Mar 17 '23 at 15:20
  • If you look in the network tab in the browser, you should be able to see the request. My first guess would be that it gets blocked due to CORS, and that you need to add `localhost:` as an [allowed origin](https://fastapi.tiangolo.com/tutorial/cors/). – M.O. Mar 17 '23 at 15:37
  • Forgot to mention that console.log(data) show nothing! – jolaxbeat Mar 17 '23 at 16:15
  • Does this answer your question? [React not showing POST response from FastAPI backend application](https://stackoverflow.com/questions/71802652/react-not-showing-post-response-from-fastapi-backend-application) – Chris Mar 17 '23 at 16:48
  • You might also find [this answer](https://stackoverflow.com/a/73963905/17865804), as well as [this answer](https://stackoverflow.com/a/73761724/17865804) and [this answer](https://stackoverflow.com/a/71741617/17865804) helpful – Chris Mar 17 '23 at 16:49

1 Answers1

3

As mentionned by M.O in the comments, FastApi is running on 'http://localhost:8000' meanwhile React on 'http://localhost:3000' this created an issue where the browser will block requests from the React app to the FastAPI API by default due to CORS. Therefore, i needed to enable CORS on the FastAPI API and add http://localhost:3000 to the list of allowed origins like this :

from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"], # here
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

I hope this will help other beginners and thanks for the help everyone!

jolaxbeat
  • 41
  • 3