PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, September 4, 2022

[FIXED] How to fetch data from password protected API in JavaScript?

 September 04, 2022     api, authentication, javascript, json, python     No comments   

Issue

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.


Solution

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.



Answered By - Lalaluka
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing