Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next.js fetch request gives error TypeError: fetch failed [duplicate]

I'm setting up a next.js website with strapi but running into an issue with my fetch request. When I make the request in postman I can see the data is returned so the endpoint is correct.

The error I get is TypeError: fetch failed in my console I get

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:1337
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 1337
  }
}

In my page template, I have

import React from "react";

import Layout from "@/components/Layout/Layout";
import { fetcher } from "@/lib/api";

const Insights = () => {
  return (
    <Layout>
      <p>Insights</p>
    </Layout>
  );
};

export default Insights;

export async function getServerSideProps() {
  const insightsResponse = await fetcher(
    "http://localhost:1337/api/insights"
  );
  return {
    props: {
      insights: insightsResponse,
    },
  };
}

My fetcher function is

export async function fetcher(url: string, options = {}) {
  let response;

  if (!options) {
    response = await fetch(url);
  } else {
    response = await fetch(url, options);
  }

  const data = await response.json();

  return data;
}
like image 244
CIB Avatar asked Sep 02 '25 15:09

CIB


1 Answers

Use 127.0.0.1 instead of localhost it will work

like image 75
NIsham Mahsin Avatar answered Sep 05 '25 06:09

NIsham Mahsin