I am trying to make a simple api request to fetch some data for trending movies of the week. I do not see it in the web browser console though. Any suggestions? This is the first API that I have tried on my own. I am a coding bootcamp graduate. Anything thing helps!
here is the repository:https://github.com/JoelGetzke/JoelsMovies
Here is the code:
const apiKey = '535b82486819425b363ecd51e605db3c';
const apiUrl = 'https://api.themoviedb.org';
// Example endpoint to get a list of movies
const endpoint = `${apiUrl}/3/trending/movie/week`;
// Constructing the request URL with API key
const requestUrl = `${endpoint}?api_key=${apiKey}`;
// Making a GET request using fetch API
fetch(requestUrl)
.then(response => {
// Check if the response is successful (status code 200)
if (response.ok) {
// Parse the JSON response
return response.json();
}
// If response is not successful, throw an error
throw new Error('Network response was not ok.');
})
.then(data => {
// Do something with the data
console.log(data);
})
.catch(error => {
// Handle errors
console.error('There was a problem with the fetch operation:', error);
});
I tried to refresh the page and open up the browser consol.log. It is currently reading:
index.html:89
GET http://127.0.0.1:5500/main.js net::ERR_ABORTED 404 (Not Found)
index.html:1 Refused to execute script from ‘http://127.0.0.1:5500/main.js’ because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled.
2
Answers
I can’t recall exactly how response.json() works but I have a feeling it ‘runs’ its input as regular JavaScript, which means if the MIME type returned by the server isn’t application/javascript then it might not recognise it as runnable code. (Perhaps!)
First, try dumping/inspecting the data you get back from the server to double check it is indeed plain JSON. Then use JSON.parse() instead of response.json() to turn it from a string into an object. If the MIME type is indeed the problem, then JSON.parse() will work so long as you feed it a string, regardless of how the network headers described that string.
Your browser fail to load the
main.js
file because the file is in different directory (assets
) that’s why you got 404 as result.Try:
<script src="./assets/main.js">