Home > Enterprise >  How to fetch data from password protected API in JavaScript?
How to fetch data from password protected API in JavaScript?

Time:08-04

I am trying to fetch data from API which needs a username and password to access it. I was able to fetch this data in python using verify=False but was unable to do the same in JavaScript. I am facing errors related to CORS (Cross-origin resource sharing). Below is the code I am using:

getzuuldata(){
     fetch('URL', {
             "verify": false,
             "mode": 'no-cors',
             "auth": ["abcd", "aaaaaaaaa"]
         }).then(function (response) {
                 if (!response.ok) {
                     console.log('Error with status code'   response.status);
                     return;
                 }
                 response.json().then(function (data) {
                     var is_failing = data["data"]["result"][0]["value"].slice(-1);
                     console.log("hello" , is_failing);

                 });
             })
             .catch(function (err) {
                 console.log('Error:'   err)
             })

       }

This should print the JSON data present in the API in URL but result in the below errors:

Access to fetch at 'URL' 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.
(index):827          GET url net::ERR_FAILED 401
getzuulData @ (index):827
click_service @ (index):1597
(anonymous) @ d3.min.js:1
(index):842 Error:TypeError: Failed to fetch

I tried disabling the CORS in Browser and setting it to no CORS but it did not work.

CodePudding user response:

You need to disable CORS on the Server, not the Client. CORS is a protection mechanism for Servers. Here is a short explanation Video about cors. Setting your mode: 'no-cors' will not help you. It actually might make it worse.

Your Python Code works because the Request does not originate from a "Website" it originates from a Server so no Origin will be set. Your Javascript, however, originates from a Browser and the Browser will send the origin for example localhost:8080 so the Server with activated CORS will block it.

  • Related