I'm trying to access a balldontlie API endpoint to be able to add a search bar to my web project through a template I found online, but I'm running into a CORS error while implementing this. The exact statement says ":5500/hoops.html?search=Lebron#:1 Access to fetch at 'https://www.balldontlie.io/api/v1/players?search=Lebron' from origin 'http://127.0.0.1:5500' 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."
This is what the code loos like:
const options = {
mode: 'cors',
'Authorization': "myAPIKey", // i have my own, just hiding it for the post//
method: 'get',
}
function searchPlayer() {
//retrieve info from input
const playerNameInput = document.querySelector("#playerInput");
//trims name whitespace
const playerName = playerNameInput.value.trim();
//if player name is blank, alert is shown and ends functionality
if (playerName === "") {
alert("Please enter a player name");
return;
}
const apiUrl = "https://www.balldontlie.io/api/v1/players?search=" + playerName;
//fetch data from the api (plus the appended player)
fetch(apiUrl, options)
//converts api response to json format
.then(response => response.json())
//executes after data is fetched
.then(data => {
//if there is a player in the array =
if (data.data.length > 0) {
//player variable contains data from the first player found in the api response
const player = data.data[0];
//calls function to display player info
printPlayerInfo(player);
Ive went to other posts with this issue but im still finding difficulties. Someone suggested to add these lines to the back-end.
Access-Control-Allow-Origin: 'http://127.0.0.1:5500';
Access-Control-Allow-Credentials: true;
Access-Control-Allow-Methods: GET, POST, OPTIONS;
Access-Control-Allow-Headers: Origin, Content-Type, Accept;
I don't know what that does or how it would help. Any Advice is appreciated, thank you.
I tried to go around copying and pasting solutions that didn't include going through a third party but I dint find what I was looking for. I'm fairly new to javascript and I'm learning as I go with this project using html, css, and barebones javascript. I dont want to go into angular or react yet.