-4

I'm encountering a CORS-related issue while trying to make a fetch request from my JavaScript code. The error message I'm seeing is:

"Access to fetch at 'https://regres.in/api/users' from origin 'http://127.0.0.1:5501' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

I've attempted to retrieve data from the "https://regres.in/api/users" endpoint using the following code:

fetch("https://regres.in/api/users")
  .then((message) => message.json())
  .then((message) => console.log(message));

The code seems correct, but I'm encountering this CORS-related issue. As a context, I'm running this code on my local development environment using a basic HTML file and JavaScript. I don't have control over the server at "https://regres.in," so I'm unable to modify the server's response headers.

I'd like to understand why I'm facing this issue and whether there's a reliable solution that doesn't involve modifying the server's configuration.

Any insights or suggestions on how to approach and resolve this issue would be greatly appreciated. Thank you in advance for your help.

I expected that upon running the fetch code I would successfully retrieve the user data from the endpoint and log it to the console.

What Actually Resulted:

Unfortunately, the fetch request didn't proceed as I had hoped. Instead, I encountered the following CORS error message:

many of the solutions I've come across are centered around React, while I'm still learning the basics of JavaScript and HTML.

Despite searching for solutions, I haven't been able to find a straightforward answer that fits my current skill level and situation. I'm hoping to gain a better understanding of the root cause of this issue and discover a feasible solution that allows me to access the data as intended.

devbams
  • 1
  • 1
  • 3
    There are hundreds of questions like this, didn't your research explain why it happens? You need to do the fetch from your server, not the client. – Barmar Aug 07 '23 at 19:46
  • @Barmar can you kindly reply with a link that talks about this particular problem also I am new to APIs so I do not know what you mean by "fetch from your server, not the client". can you please explain? – devbams Aug 07 '23 at 19:50
  • 2
    Click on the `cors` tag and you'll find hundreds of questions about it. – Barmar Aug 07 '23 at 19:54
  • 1
    You write an API on your server in whatever language you want. It calls the real API, and passes the result back. – Barmar Aug 07 '23 at 19:54

0 Answers0