Fetch CORS errors

Question:

When I make a http req with fetch in javaScript

Get This Error In console

test.ulvhgujdfd14.repl.co/:1 Access to fetch at 'https://api.binance.com/api/v3/userDataStream' from origin 'https://test.ulvhgujdfd14.repl.co' has been blocked by CORS policy: Request header field x-mbx-apikey is not allowed by Access-Control-Allow-Headers in preflight response.
(index):24     POST https://api.binance.com/api/v3/userDataStream net::ERR_FAILED
(anonymous) @ (index):24
(index):27 error TypeError: Failed to fetch
    at (index):24:5

Console Screen:

Network Screen:


Repl link:

https://replit.com/@ulvhgujdfd14/TEST

My Html & JS Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>

    var myHeaders = new Headers();
    myHeaders.append(
      "X-MBX-APIKEY",
      "My API HERE"
    );
    myHeaders.append(
      "Content-Type", "text/plain"
    );
    var requestOptions = {
      method: "POST",
      headers: myHeaders,
    };
    
    fetch("https://api.binance.com/api/v3/userDataStream", requestOptions)
      .then((response) => response.text())
      .then((result) => console.log(result))
      .catch((error) => console.log("error", error));

      
    </script>
  </body>
</html>

Please Help

When you try to send a request to another domain (other than your site’s domain), the browser blocks this request.

To prevent blocking, try adding this property to your RequestOptions object:

mode: 'no-cors'

I did That but now status code 401

Although I don’t need any Authentication If I run this local with
node test.js
It will run normally and return the response

After some research, I know what this error is.

Cross-Origin Resource Sharing (CORS)

This will simply block any connection from your domain to any different domains, and this only exists in browsers, so if you make the same request with Python or any other backend language on the server, not the browser, you will receive the response normally.

There is a way to overcome this problem, but with some limitations: JSONP

I hope this helps anyone.

3 Likes

I usually just use UNCORS.

fetch("https://uncors.vercel.app/?url=https://yourendpoint.com")
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.