skip to Main Content

I’ve been trying this end-point but I can’t make a fetch.
On postman and the web-browser I get data, but not the case with fetch using React

this is the end point:
http://monedaextranjera.ansolidata.com/data/?format=json

the Error says:

Access to fetch at ‘http://monedaextranjera.ansolidata.com/data/?format=json’ from origin ‘http://localhost:5173’ 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 tried using fetch and axis

2

Answers


  1. To resolve this issue, you have a few options:

    CORS Headers (Recommended): The best practice is to configure the server hosting the API to include Cross-Origin Resource Sharing (CORS) headers. CORS headers specify which origins are allowed to access the resources on the server. You should contact the owner of the API and request that they configure their server to allow requests from your React application’s domain.

    Proxy Server: Set up a proxy server on your backend (if you have one) that acts as an intermediary between your React application and the API. Your React app makes requests to the proxy server, and the proxy server forwards those requests to the API. This way, you bypass the Same-Origin Policy. However, this approach adds complexity to your server-side code.

    JSONP (Only If Supported by the API): If the API supports JSONP (JSON with Padding), you can use it to bypass the Same-Origin Policy. JSONP is a technique that involves loading JSON data as a script, which is allowed to make cross-origin requests. Be aware that JSONP has some security considerations and is not as widely supported as CORS.

    Browser Extension: You can also use browser extensions like "Allow CORS" or "CORS Unblock" to temporarily disable the Same-Origin Policy during development. However, this is not a recommended solution for production use.

    To implement CORS correctly, you should work with the owner of the API to configure the necessary headers on their server. This ensures a secure and compliant solution.

    Login or Signup to reply.
  2. set the fetch property to mode: ‘cors’

    (https://developer.mozilla.org/en-US/docs/Web/API/Request/mode)

    fetch('http://monedaextranjera.ansolidata.com/data/?format=json', {
                mode: 'cors',
                method: "post",
                headers: {
                     "Content-Type": "application/json"
                },
                body:....
     })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search