I'm trying to make an api request and I do get the data because I tried console logging it and it shows on the console but I still get errors. Here are the errors:
TypeError: res.json is not a function
Error: Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?
Here is my code:
export async function getServerSideProps(context) {
// API KEYS
const apiKeyLocationIQ = process.env.API_KEY_LOCATIONIQ;
const apiKeyWeather = process.env.API_KEY_WEATHER;
// API REQUEST OPTIONS
let cityLocationIQ = context.params.location;
let urlLocationIQ = "https://api.locationiq.com/v1/search.php?format=JSON&key="+apiKeyLocationIQ+"&q="+cityLocationIQ+"&limit=1";
// API REQUEST FOR LAT AND LON
try{
const res = await axios.get(urlLocationIQ).then((resLocation)=>{
return resLocation
})
const weather = await res.json();
return {
props: {
weather
}
}
}catch (error){
console.log( error);
}
}
UPDATE I made some changes to the axios request and I get a different error. This time it says:
function cannot be serialized as JSON. Please only return JSON serializable data types.
here is how my updated axios request looks like:
try{
const res = await axios.get(urlLocationIQ, {responseType: 'json'})
const weather = await res;
return {
props: {
weather
}
}
}catch (error){
console.log( error);
throw error;
}
FINAL UPDATE So it turns out that the axios request that I sent returns the entire request data including the headers etc. and the data that I needed was an object at the very bottom of the response, so all I had to do was to specify the data I needed. Here is my code:
const location = await axios.get(urlLocationIQ).then((resLocation)=>{
return {resLocation.data[0]}
})
After that, the code works perfectly now.