Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
How to use a third-party API inside next/api?

I am new to NEXTJS and creating a weather application .I am using a openweather api but how can I use it inside the next/api. I had tried by creating a file today.js inside next/api and wrote the code it in this way but I am unable to get data in console ?

today.js

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fecthInfo = async() => {
    const response = await fetch(url);
    const data = await response.json() ;
    return data;
}
export default function handler(req, res) {
    const result = fecthInfo();
    console.log(result)
    res.status(200).json(result)
  }

Can you tell the mistake I am doing , or I have to simply use the fetch method in any component like in reactJS.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Looks like you are missing an async/await. This should work:

const apikey = process.env.REACT_APP_API_KEY_1;
const url = `https://api.openweathermap.org/data/2.5/weather?q=Bhopal&appid=${apikey}`;

const fetchInfo = async() => {
    const response = await fetch(url);
    const data = await response.json();
    return data;
};

export default async function handler(req, res) {
    const result = await fetchInfo();
    console.log(result);
    res.status(200).json(result);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of fetching data from a remote api inside the api route. I suggest to use the getServerSideProps() in the route page directly so you have to fetch the data just once.

You pass the requested data through props to the Test component.

const Test= function({data}){
 console.log(data)
 return <div></div>
}



export default async function 
getServerSideProps(){
const response = await fetch(url);
const data = await response.json();
 return {
  props:{data}
 }
}

 export default Test; 
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda