0

Using the below to access an api using python and it gives me a successful response. Trying to do the same thing from an html file with JavaScript on my hard drive I get the below error. Reading around the issue seems to be that I am running this from a local file not hosted on a proper server.

Access to fetch at 'https://api.connect.example.com/test/v1/state-pop/levels/rating?' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains the invalid value ''. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

import requests
import json
from requests.auth import HTTPBasicAuth

headers = { 'Accept': 'application/json' }
auth = ('user','password')
response_API = requests.get('https://api.connect.example.com/test/v1/state-pop/levels/rating?', auth = auth, headers=headers)
<!doctype html>
<html>
    <head>
<script>
let username = 'username';
let password = 'password';

fetch('https://api.connect.example.com/test/v1/state-pop/levels/rating?', {
  method: 'get',
  headers: {
    "Content-Type": "text/plain",
    'Authorization': 'Basic ' + btoa(username + ":" + password)
  }
})
</script>
</head>
</html>
CGarden
  • 169
  • 17

1 Answers1

1

You can use this simple extension for your browser to avoid CORS issues also from your html file: https://mybrowseraddon.com/access-control-allow-origin.html

After the installation complete you need to toggle on the extension in the 'problematic' site:

Toggle on CORS extension after installation

(in the bottom of the picture you can see the toggle button 'ON' - just click it :))

Daniel Agam
  • 209
  • 1
  • 9
  • May be worth understanding why the server in question indicates domain restrictions rather than simply circumventing CORS entirely. – jarmod May 27 '22 at 11:03