Err: fetching data via API works on localhost but doesn't work on live server
Okoli Evans
Posted on September 7, 2022
As a young developer, there are some minor bugs you might encounter that will be pretty confusing. Every new developer, and even experienced devs encounter this every now and then. The thing about software development is that a single comma, semicolon or colon in a wrong place will likely make your code not compile, or render an element or function undefined.
When I started out newly, I once spent two days searching for a bug, only to find out that the issue was just a '}' in a wrong place... bugs are completely normal.
So I was working on a demo movie app some time ago, it happened that the API fetch and every components worked perfectly on localhost, but wasn't fetching when deployed on live server. It was really confusing for me then that I had to abandon the project altogether. Recently I was going through my repositories and found the abandoned project, so I decided to try and fix it.
Issue:
const handleSubmit = async () => {
setLoading(true);
const response = await fetch(
`http://www.omdbapi.com/?s=${searchParam}&apikey=70c11897`
);
const data = await response.json();
console.log(data);
if (data) {
setMovieList(data.Search);
localStorage.setItem("movieList", JSON.stringify(data.Search));
setLoading(false);
setSearchParam("");
}
};
It turned out that the problem was a very simple one. The API URL I was using was 'http://apiurl.com/key'. Now the problem is most web engines don't render insecure links, so my API URL was blocked from fetching data on live server. The simplest solution right? All I needed to do was add 's' to the 'http' like so 'https://apiurl.com/key'.
Fixed:
const handleSubmit = async () => {
setLoading(true);
const response = await fetch(
`https://www.omdbapi.com/?s=${searchParam}&apikey=70c11897`
); //notice the 's' now added to 'http'
const data = await response.json();
console.log(data);
if (data) {
setMovieList(data.Search);
localStorage.setItem("movieList", JSON.stringify(data.Search));
setLoading(false);
setSearchParam("");
}
};
Like I said, some bugs can be pretty confusing for beginners, but hey, even the best developers were once beginners and coding is one skill that requires tenacity, determination and resourcefulness. So when you encounter a bug, seek for solution on open source websites or ask experienced devs for help. I hope this helps someone. ☺
Posted on September 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.