cra*_*gib 21 javascript fetch-api next.js
我正在使用 Strapi 设置一个 next.js 网站,但我的获取请求遇到了问题。当我在邮递员中发出请求时,我可以看到返回的数据,因此端点是正确的。
我得到的错误是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
}
}
Run Code Online (Sandbox Code Playgroud)
在我的页面模板中,我有
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,
},
};
}
Run Code Online (Sandbox Code Playgroud)
我的获取器功能是
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;
}
Run Code Online (Sandbox Code Playgroud)
在 codegrepper 中引用视频出现此错误是因为您使用的是节点版本 18 或更高版本,其中 fetch 由节点给出。因此,您必须使用低于 18 的节点才能在 getServerSideProps 中进行 fetch 工作。您可以使用 nvm 来控制要使用的节点版本。
您还可以提供要获取的 url 的完整路径,而不是更改节点版本,而不是 /api/listings/property_type 给出 http://localhost:3000/api/listings/property_type
小智 -2
您能打开开发工具查看响应代码吗?我看到 ECONNREFUSED 意味着服务器拒绝了此请求。确保您请求的数据正确(您也可以在“网络”选项卡中检查)
请参考此文档 https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch 有更多选项,比如 method、headers(headers 字段非常重要)、... 添加这些请求选项并重试。
| 归档时间: |
|
| 查看次数: |
46092 次 |
| 最近记录: |