next.js 为什么在getStaticProps中从www.example.com获取数据127.0.0.1有效,而从localhost获取数据无效?

xyhw6mcr  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在从监听getStaticProps中端口5000的flask API中获取数据。我注意到获取http://127.0.0.1:5000/posts有效,但http://localhost:5000/posts无效。同样的问题也发生在getServerSideProps上。但如果我从客户端获取,两个url都有效。
下面是我的代码:

import axios from "axios";

export default function SSG({ data }: { data: any }) {
  return <div>SSG</div>;
}

export async function getStaticProps() {
  const res = await axios.get("http://localhost:5000/posts");

  return {
    props: {
      data: res["data"],
    },
  };
}

下面是错误消息:

error - AxiosError: connect ECONNREFUSED ::1:5000
    at AxiosError.from (webpack-internal:///./node_modules/axios/lib/core/AxiosError.js:94:14)
    at RedirectableRequest.handleRequestError (webpack-internal:///./node_modules/axios/lib/adapters/http.js:550:75)
    at RedirectableRequest.emit (node:events:513:28)
    at eventHandlers.<computed> (/Users/tdawg/Desktop/axios-test/node_modules/follow-redirects/index.js:14:24)
    at ClientRequest.emit (node:events:513:28)
    at Socket.socketErrorListener (node:_http_client:481:9)
    at Socket.emit (node:events:513:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  port: 5000,
  address: '::1',
  syscall: 'connect',
  code: 'ECONNREFUSED',
  errno: -61

这似乎不像是一个axios的问题,因为我观察到同样的,即使与未来13的fetch
为什么127.0.0.1可以工作而localhost不能?

piah890a

piah890a1#

127.0.0.1地址指定IPv4,看起来localhost正在解析为IPv6(即address: '::1')。
可能您的软件环境没有针对IPv6正确设置。

相关问题