Katharina Schreiber
Katharina Schreiber

Reputation: 1371

NEXT.js fetch internal API route

I am trying to outsource the function fetchCityData in lib/cityData and use it later in different components. And I have a next.js App, where I use api routes for external API calls. So it is a bit complex, but my boss wants me to proceed like that. Lets start with

lib/cityData.js

const fetch = require('cross-fetch');

const fetchCityData = (city) => {  
  const options = {
    method: `POST`,
  };
  fetch(`http://localhost:3000/api/weather?city=${city}`, options)
  .then((response) => {
    if(response.ok){
      return response.json().then(data => console.log(data))
      
    }
      throw new Error('Api is not available') 
    })
  .catch(error => {
    console.error('Error fetching data: ', error)
  })
}
fetchCityData('London')
module.exports.fetchCityData = fetchCityData;

For now I was just trying to test this code in the console. If I use fetch(/api/weather?city=${city}) I get TypeError: Only absolute URLs are supported. If I go with a full URL just to test it out, I get Error fetching data: FetchError: request to http://localhost:3000/api/weather?city=London failed, reason: connect ECONNREFUSED 127.0.0.1:3000. That is after I added proxy to my package.json. Before I couldn't fetch too. I also tried to add development and production URL to my .env.local file - this also didn't fix the problem. Is there a solution to that?

Upvotes: 3

Views: 7405

Answers (1)

Katharina Schreiber
Katharina Schreiber

Reputation: 1371

Adding server and env solved the problem

const fetch = require("cross-fetch");
const dev = process.env.NODE_ENV !== "production";
const server = dev
  ? "http://localhost:3000"
  : "https://your_deployment.server.com";

const fetchCityData = (city) => {
  const options = {
    method: `POST`,
  };
  fetch(`${server}/api/weather?city=${city}`, options)
    .then((response) => {
      if (response.ok) {
        return response.json().then((data) => console.log(data));
      }
      throw new Error("Api is not available");
    })
    .catch((error) => {
      console.error("Error fetching data in city data: ", error);
    });
};
//fetchCityData('London')
module.exports.fetchCityData = fetchCityData;

Upvotes: 7

Related Questions