0

I have created an HTML file, and there I have implemented a fetch request from Javascript. But is it saying blocked by CORS policy. How do I remove this error?

My code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <!-- <meta name="viewport" content="width-device-width ,initial-scale=1.0"> -->
        <meta http-equiv="X-UA-Compatible" content="ie-edge">

        <script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous"></script>
        <title>Document</title>

        <script type="text/javascript">
            fetch("http://ec2-13-233-168-148.ap-south-1.compute.amazonaws.com:8181/v1/youtube/detail?url=https://www.youtube.com/watch?v=FS9dkwhPypY").then(

                res=>{
                    res.json().then(
                        data=>{
                            console.log(data.videoDetails.keywords.length);
                console.log(data.videoDetails.thumbnail.thumbnails.length)           


                        })
                    });

        </script>

    </head>
    <body>
      <div class="container">   
      <table class="table table-stripped">
        <thead>
            <tr>

                <th>Url</th>
                <th> height</th>
            <th>width </th>
            </tr>
        </thead>

        <tbody id="th"></tbody>

      </table>
       <table class="table table-stripped">
        <thead>
          <tr>


            <th>Keyword</th>
          </tr>
        </thead>
        <tbody id="data"></tbody>
      </table>
    </div>
    </body> 
    </html>

My fetch request is not working in this condition. It says:

Access to fetch at 'http://ec2-13-233-168-148.ap-south-1.compute.amazonaws.com:8181/v1/youtube/detail?url=https://www.youtube.com/watch?v=FS9dkwhPypY' from origin 'null' 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.

How might I fix this issue ?

Jij
  • 105
  • 1
  • 2
  • 12
Anurag Mishra
  • 647
  • 3
  • 15
  • 31

1 Answers1

1

This is normally happens when your client requesting a resource from a different endpoint (which is different from the your browser URL) other than the client's origin.

So, you will have to enable CORS from your backend web server to solve this problem. The configurations will be vary based on the web server you are using. Please go through below

For Apache
Add below line into your virtual host

Header set Access-Control-Allow-Origin "*"

For Nginx
Add below line into your relevant nginx config file.

add_header Access-Control-Allow-Origin *;
chamindaindika
  • 455
  • 3
  • 15