簡體   English   中英

next.js 獲取請求給出錯誤類型錯誤:獲取失敗

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

我正在使用 strapi 建立一個 next.js 網站,但我的獲取請求遇到了問題。 當我在 postman 中發出請求時,我可以看到數據已返回,因此端點是正確的。

我得到的錯誤是TypeError: fetch failed in my console 我得到

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
  }
}

在我的頁面模板中,我有

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,
    },
  };
}

我的抓取器 function 是

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;
}

reference with video in codegrepper發生此錯誤是因為您使用的是節點版本 18 或更高版本,其中節點提供了獲取。 所以你必須使用低於 18 的節點來使獲取在 getServerSideProps 中工作。你可以使用 nvm 來控制你想要使用的節點版本。

你能打開開發工具並檢查響應代碼嗎? 我已經看到 ECONNREFUSED 意味着服務器拒絕了這個請求。 確保您請求的數據正確(您也可以在“網絡”選項卡中查看)

請參考此文檔https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch有更多選項,比如method,headers(headers字段很重要),... 添加這些請求選項,然后重試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM