0

I'm currently working on a JavaScript project and encountering a CORS error when making a cross-origin request from my application. Here are the details:

I am using a https://haveibeenpwned.com/API/v3 Documentation Here is the code . The api request should me made using sending key on the header .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Have I Been Pwned</title>
</head>
<body>

    <h1>Hello</h1>

    <script>
        const apiKey = "333a2*********b2ea641*********";
const url = "https://haveibeenpwned.com/api/v3/breachedaccount/example@test.com"; 

const headers = {
  "hibp-api-key": apiKey,
};

const options = {
  method: "GET",
  headers: headers
};

fetch(url, options)
  .then(response => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("Request failed with status: " + response.status);
    }
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

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

And I have check this API key and all using Insomnia i am getting response from the header . But in browser I am keep getting this error .

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

  • Where are you running the request from in the browser? Localhost (or a blank page) can cause CORS issues: https://stackoverflow.com/a/10892392/21148174 – offscriptdev Jun 14 '23 at 03:09

1 Answers1

0

Cors error occur when we try to share resource between two different frameworks. If you are using any framework try to install and configure cors. Read more about cors on this page: https://www.npmjs.com/package/cors.

And according to the documentation, you need to define your user agent in the request header.

user-agent: YOUR-USER-AGENT

Hope this can resolve the issue.

skmishra
  • 1
  • 3