如果我使用浏览器访问localhost:1337/API/events作为PUBLIC(未经身份验证的用户),我会返回以下内容:
{"data":[{"id":1,"attributes":{"name":"Throwback Thursday with DJ Manny Duke","slug":"throwback-thursday-with-dj-manny-duke","venue":"Horizon Club","address":"919 3rd Ave New York, New York(NY), 1002","date":"2022-07-20T02:00:00.000Z","time":"10:00 PM","createdAt":"2022-04-12T02:05:08.246Z","updatedAt":"2022-04-12T02:17:16.760Z","publishedAt":"2022-04-12T02:05:16.192Z","performers":"DJ Manny Duke","description":"Description for the vent of DJ Manny Duke"}},{"id":2,"attributes":{"name":"Boom Dance Festival Experience","slug":"boom-dance-festival-experience","venue":"Blackjacks","address":"123 Lexington","date":"2022-04-25T16:00:00.000Z","time":"8:00 PM","createdAt":"2022-04-12T02:26:32.123Z","updatedAt":"2022-04-12T02:26:33.540Z","publishedAt":"2022-04-12T02:26:33.538Z","performers":"DJ LUKE, DJ BLACKJACK","description":"Whatever Description"}},{"id":3,"attributes":{"name":"Encore Night Boat Party","slug":"encore-night-boat-party","venue":"Encore","address":"12343 New York","date":"2022-11-14T16:00:00.000Z","time":"7:00 PM","createdAt":"2022-04-12T02:28:06.028Z","updatedAt":"2022-04-12T02:28:36.292Z","publishedAt":"2022-04-12T02:28:07.622Z","performers":"BAD BOY BILL","description":"Description of Encore"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":3}}}
然而,当我使用Next.JS访问相同的链接时,我得到:
FetchError: request to http://localhost:1337/api/events failed, reason: connect ECONNREFUSED ::1:1337
为什么斯特拉皮拒绝连接?如何修复?
config/index.js
export const API_URL =
process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337'
pages/index.js
...
export async function getStaticProps() {
const res = await fetch(`${API_URL}/api/events`)
const events = await res.json()
return {
props: { events: events.slice(0, 3) },
revalidate: 1,
}
}
-----已将代码更新至以下,但仍拒绝连接----
config/index.js export const API_URL = 'http://localhost:1337'
pages/index.js
export async function getStaticProps() {
const res = await fetch(`${API_URL}/api/events`, {
headers: {
Authorization: `bearer thetoken`,
},
})
const events = await res.json()
return {
props: { events: events.slice(0, 3) },
revalidate: 1,
}
}
----下面是错误的屏幕截图,显示客户端(NEXT.JS)和服务器(STRAPI)的2个控制台都在运行----
6条答案
按热度按时间bis0qfac1#
yvt65v4c2#
指定127.0.0.1:1337而不是localhost解决了这个问题
ie3xauqp3#
我遇到了同样的问题,直到我发现问题是我的节点版本高于v16
t1rydlwq4#
我也遇到了同样的问题,我注意到了一些事情并纠正了它。
1.这是在我将我的节点版本从v16更新到v18之后发生的。
1.显示的错误将我的地址显示为
::1:1337
,而不是API URL。localhost
在我的next.js项目中不再工作。所以,我在env文件中对我的API URL做了两个更改,它对我有效。
1.将
localhost
更改为127.0.0.1
。1.用引号将API URL括起来,这样它就可以将其视为字符串。
"127.0.0.1"
。carvr3hs5#
在你的获取,你需要通过一个不记名授权令牌从Strapi.您将在
Strapi Admin > Settings > API tokens > Create new API token
中找到令牌,现在复制新令牌并在fetch调用中使用它。例如,您的令牌是XYZ123
。这样使用它:lhcgjxsq6#
.env bad localhost:1337 127.0.0.1:1337