0

I'm trying to get data using axios, but facing the following error:

No 'Access-Control-Allow-Origin'

I have tried to find a solution, but nowhere I found a proper solution including FastAPI, React and Axios.

Here is my backend:

origins = ['https://localhost:3000', 'https://localhost:8080']

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


@app.get('/')
def root():
    return {
        "Data" : "Working!"
    }

Below is my frontend:

const message = async () => {
    try {
      let res = await axios.get("http://127.0.0.1:8080/");
      let result = res.data;
      console.log(result);
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    message();
  }, []);

The error:

Access to XMLHttpRequest at 'http://127.0.0.1:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Now I'm using it locally adding proxy in package.json file. But in production, it doesn't work. However, I need a proper solution for production level without using proxy.

Please help me to solve this error.

Chris
  • 18,724
  • 6
  • 46
  • 80
  • Access-Control-Allow-Origin-headers will not be added if the backend responds with a 500 internal server error - what is the actual response from the server? Also remember that in production the host probably won't be 'localhost' as the origin address. – MatsLindh Oct 12 '22 at 10:05
  • Please have a look at [this answer](https://stackoverflow.com/a/73963905/17865804) and [this answer](https://stackoverflow.com/a/71805329/17865804). – Chris Oct 12 '22 at 10:26
  • @MatsLindh here it is: **Request URL: http://localhost:8080/ Request Method: GET Status Code: 200 Referrer Policy: strict-origin-when-cross-origin access-control-allow-credentials: true content-type: application/json Accept: application/json, text/plain, */* Cache-Control: no-cache Host: localhost:8080 Origin: http://localhost:3000 Pragma: no-cache Referer: http://localhost:3000/ Sec-Fetch-Mode: cors** – Shazzadur Rahman Oct 12 '22 at 12:35
  • @Chris I fixed this in back-end: `origins = ['http://localhost:3000']` and front-end: `let res = await axios.get("http://localhost:8080/"); let result = res.data;` still getting the same error **Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.** and **GET http://localhost:8080/ net::ERR_FAILED 200** this error – Shazzadur Rahman Oct 12 '22 at 12:37
  • I couldn't find what I missed – Shazzadur Rahman Oct 12 '22 at 12:40
  • @Chris At first I was working it using proxy to overcome this error but when I hosted in aws for production, the proxy is not working. So now I am running it locally. In locally, response body: **Failed to load response data: No data found for resource with given identifier** status code: 200 – Shazzadur Rahman Oct 12 '22 at 13:07
  • 1
    Ok the problem just solved. I just set the origin port in **allow_origin** value directly instead taking it in a variable **origin**. The code before facing error: `origins = ['https://localhost:3000', 'https://localhost:8080'] app.add_middleware( CORSMiddleware, allow_origins = [origins], allow_credentials = True, allow_methods = ["*"], allow_headers = ["*"] )` The code after: `app.add_middleware( CORSMiddleware, allow_origins = ['https://localhost:3000'], allow_credentials = True, allow_methods = ["*"], allow_headers = ["*"] )` – Shazzadur Rahman Oct 13 '22 at 19:32
  • 1
    This is it. No big changes. I don't know but couldn't get the difference. Anyways it worked and thank you both for response. – Shazzadur Rahman Oct 13 '22 at 19:36

1 Answers1

1

You should use allow_origins=origins, without the brackers [] around the origins variable.

Example

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

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

Please have a look at this answer and this answer for more details.

Chris
  • 18,724
  • 6
  • 46
  • 80