简体   繁体   中英

FetchError: request to http://localhost:1337/api/products failed, reason: connect ECONNREFUSED 127.0.0.1:1337

I am trying to build an e-commerce site with Next.JS and Strapi. Whenever I try to request data from Strapi to Next.JS, I always get error:-

FetchError: request to http://localhost:1337/api/products?populate=* failed, reason: connect ECONNREFUSED 127.0.0.1:1337

?populate= * in the link is to receive all data and I also tried without it.

This is how I am requesting data:-

export async function getServerSideProps() {
  let data = await fetch('http://localhost:1337/api/products?populate=*', {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer api-token',
    },
 });
 let products = await data.json();
 return {
   props: { products },
 };
}

I have read many similar questions but can't find anything. I have checked everything many times but still not working. However, when I make the request with the same API token using thunder client , it gives me a status: 200 , and I also receive data in JSON format without any error. It's been hours and everything looks good but still not working.

First and foremost, when fetching from your nextjs api, you don't call the full url, (ie, 'localhost'), you just start the call with /api/more/params

export async function getServerSideProps() {
  // next api routes use a proxy under the hood,
  // so you just need to call `/api/` then the rest of the params :)
  let data = await fetch('/api/products?populate=*', {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer api-token',
    },
 });
 let products = await data.json();
 return {
   props: { products },
 };
}

I also think it's first going to be worth reading (and will likely answer your question) the documentation on getServerSideProps

It can be tempting to reach for an API Route when you want to fetch data from the server, then call that API route from getServerSideProps. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both getServerSideProps and API Routes running on the server.

While this may not entirely solve the problem, given then lack of further details, both these recommendations should certainly be a good start and get us goin on solving this!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM