Why do I have an error: "Invalid API key: You must be granted a valid key" when trying to make a request in react App? - reactjs

So I'm using Movies API from TMDB API, and my code looks like this:
let apikey = '{my_apikey}';
let url: string = 'https://api.themoviedb.org/3/movie/apikey=';
url = url + apikey;
console.log(url);
(async function () {
const response = await fetch(url);
const data = await response.json();
console.log(data);
})()
If I insert the url along with my API it displays the data just fine, but when I'm doing it from my app, I have the next error:
I can't figure out what could be the problem, cause my api key is fine and I copied it from the website.

According to the API documentation. The URL should look something like this:
https://api.themoviedb.org/3/movie/76341?api_key=<<api_key>>

Related

Cant receive data from gitHub API

I try to receive data from gitHub API. As the name is entered in input element I send a request to
https://api.github.com/search/users?q=${username} in:login type:user.
And I`m expecting that I received all users with this username (input element may has whole username or just a part of username). But got only one user.
You can use async and await method to get your proper result.
const gitUsers = async (username) => {
const response = await fetch(`https://api.github.com/search/users?q=${username}`);
const result = await response.json();
console.log(result);
};
gitUsers("carl")

Using the API Rest of Firebase Realtime Database on React

I'm working on a little react project to store and retrieve links from firebase's realtime database, it has been a while since I used for the last time and I don't know if the thing has changed, but if I'm not wrong I think that the last time I used you could send and retrieve data through an API rest. So doing get and post requests you could store and retrieve data.
But now seems like it's not working that way anymore.
This is the code on my main component to store links on the database (I work with react query):
const mutation = useMutation(storeLink);
const saveLinkHandler = () => {
mutation.mutate({link: linkRef.current.value});
setIsModalShown(false);
};
And this is the function that performs the request (storeLink):
export const storeLink = async (link) => {
const result = await axios.post(
`${process.env.REACT_APP_API_ADDRESS}/links.json`,
{url: link}
);
console.log(result);
return result;
};
When I run this nothing crashes and the url gets stored but with a strange format like this:
I don't know what's that think between link and the actual url.
So when I try to retrieve all the results I get an strange object that I don't know how to work with.
This is the code that retrieves the links stored:
const queryLinks = useQuery("links", listLinks);
And this is the listLinks functions that retrieves the results:
export const listLinks = async () => {
console.log(`list links`);
const result = await axios.get(
`${process.env.REACT_APP_API_ADDRESS}/links.json`
);
return result.data;
};
This is the console.log I get from the result:
-MydWqKnt6udN3o-trPe:
url: "www.google.com"
It's like an object not an array of results.
I've been checking SO and Google and I couldn't find any explanation. I'm using authentication over firebase don't know if that's relevant.

React fetch local json file for testing does not work

I'm trying to fetch a .json file from local, and
I get response 200 but with a body response of HTML: "You need to enable JavaScript to run this app."
I have javascript enabled of course.
I don't want to import the file to simulate the real fetch.
How does local fetch work in react? How do I know if the fetch route is right? It doesn't give any useful error hint.
useEffect(() => {
const getData = async () => {
const dataFromLocal = await fetchData();
console.log('dataFromLocal', dataFromLocal);
}
getData();
}, [])
const fetchData = async () => {
const response = await fetch('data.json');
const data = await response.json();
return data;
}
I found how it works:
const response = await fetch('data.json',
{headers:
{'Content-Type': 'application/json','Accept': 'application/json'}
});
just add this headers object to the fetch method and it works
There are only two possibilities based on the code you've shown:
Your server is responding with the contents of an HTML resource (likely index.html) as the response to the request for data.json, or
data.json looks like this, the JSON string you provided:
"You need to enable JavaScript to run this app."
Is data.json in your project's ./public folder?

React Cors issue in one sub-domain but not another

I'm making a React application, and to do API calls in development, I have a proxy set up in my package.json:
"proxy":"https://www.metaweather.com/api/location",
I'm making an api request to a weather app like so:
export const getLocations = async (query) => {
const response = await axios.get(`/search/?query=${query}`)//full address is proxied in package.json
return response.data //WORKS PERFECTLY
}
However, I cannot make an api request to a different url of the same domain, due to a CORS error
export const getWeather = async (id) => {
const response = await axios.get(`44418`)
return response.data //CORS PROBLEM
}
How can I fix this? I've been searching all day, and cannot figure out why one subdomain will work but the other won't?
Could it be the missing '/' at the start of the zip code? Don't know what the endpoint looks like but if you've configured cors options on that /location route maybe it's not hitting it right.

Why am I getting empty array in fetch request to MongoDB from ReactJS?

I am trying to fetch all the articles from a document in MongoDB in React. It is perfectly working in Backend with NodeJS when I tested with Postman. But in Frontend , React, I am getting empty array. How to solve this.
Server.js (Backend)
app.get('/api/articles', async (req, res)=>{
const client = await MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser:true, useUnifiedTopology:true})
const db = client.db('my-blog')
const articleInfo= await db.collection('articles').find({}).toArray(function(err, result){
if (err) console.log(err)
res.status(200).send(result)
client.close()
})
})
articlePage.js (FrontEnd)
componentDidMount(){
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
const fetchdata = fetch('/api/articles/').then(res=>res.json())
.then(data=>this.setState({articles:data}))
console.log(this.state.articles)
}
Api address is set up in package.json with proxy:http://localhost:8000
How to get the documents data from MongoDB in React?
Firstly, check if you the API call went through to the server from your React app. If it has, then check for the response code in the network. In your case, 200 is where you get the desired result from the API. If you are not getting the desired result, then check your collection and document names and also arguments your are passing in the query.
As setState is not synchronized, you have to access it in the callback.
this.setState({ articles: data }, () => {
console.log(this.state.articles)
})

Resources