I'm trying to use axios to fetch json from an external API and serve it to my frontend. When I go to the route I created I see the json just fine. However, when I pass it to the frontend by hitting the end point and I console log to see if it works, I get this: frontend console log of promise
This is my backend code to fetch the external API:
app.get('/entertainment', async (req,res) => {
const respy = await axios.get(process.env.API_URL, {
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`
}
})
.then((resp) => res.send(resp.data))
.catch(e => console.log(e, "SOME ERROR"))
})
Frontend portion:
componentDidMount(){
fetch('http://localhost:8000/entertainment').then((res) => {
this.setState({
projectData: res.json()
})
}).then(res => {
console.log(this.state.projectData)
})
}
How do I resolve this promise? I thought the .then or the await would resolve it.
You are logging the promise into your console. And the promise is getting resolved by the way, as you can see in the screenshot. It is being resolved with the following object:
{
businesses: [...],
region: [...],
total
}
You're just not doing anything with it. Consider doing the following:
make request to the api on your frontend and do log the data the fetch resolves with in the console
fetch(YOUR_SERVER_URL).then((res) => res.json()).then(data => {
console.log(data);
});
Making a change to the code you've included in the edit:
componentDidMount(){
fetch('http://localhost:8000/entertainment').then((res) => res.json()).then(data => {
console.log(data)
this.setState({
projectData: data
})
})
}