I'm currently working on setting up a next.js website integrated with strapi, but I've encountered an issue with my fetch request. Oddly enough, when I test the request using Postman, the data is successfully returned, indicating that the endpoint is correct.
The error message I receive in my console is TypeError: fetch failed
.
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
}
}
Within my page template file, I have the following code:
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,
},
};
}
The fetcher function responsible for fetching the data is defined as follows:
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;
}