【问题标题】:ECONNREFUSED while trying to call Wordpress REST API from NextJS server尝试从 NextJS 服务器调用 Wordpress REST API 时出现 ECONNREFUSED
【发布时间】:2022-01-02 20:28:54
【问题描述】:

我正在尝试运行一个使用来自 WordPress REST API 的页面 slug 列表的简单示例,但我遇到了一个非常奇怪的行为。

我有一个异步函数 getPageList(),它只是使用 fetch 调用 WP API。

const getPages = async (path) => {
  return await fetch(process.env.NEXT_PUBLIC_WP_API_URL + "/pages?_fields=slug", {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
}

通过浏览器运行,调用这个方法并得到结果没有问题:

export default function Example() {
  useEffect(() => {
    getPageList().then(pages => console.log(pages))
  }, []); // OK
  return null
}

但是,如果我尝试从服务器执行相同的调用,在 getStaticProps 内部,我会收到错误 FetchError: request to http://localhost:8000/wp-json/wp/v2/pages?_fields=slug failed, reason: connect ECONNREFUSED 127.0.0.1:8000

这是代码sn-p:

export async function getStaticProps() {
  const pages = await getPageList()
  //(....)
}

如果我使用 Postman 查询此 URL,或者只是在浏览器中复制和粘贴,它也可以无缝运行。

有什么想法吗?

我正在使用 create-next-app、Node 16.13.0、Wordpress 5.8.2、PHP 7.4.3 运行使用本地开发服务器 (php -S localhost:8000)

提前谢谢你!

【问题讨论】:

    标签: javascript php node.js wordpress next.js


    【解决方案1】:

    这与我如何启动我的 PHP 内置服务器有关。将其更改为 php -S 127.0.0.1:8000 而不是 localhost:8000 可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多