I'm trying to run a simple example consuming the list of page slugs from WordPress REST API, but I'm facing a very strange behavior.
I have an async function getPageList() that simply calls the WP API using fetch.
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'
}
})
}
Running through the browser, I have no issues calling this method and getting the results:
export default function Example() {
useEffect(() => {
getPageList().then(pages => console.log(pages))
}, []); // OK
return null
}
However if I try to execute the same call from the server, inside getStaticProps, I receive the error FetchError: request to http://localhost:8000/wp-json/wp/v2/pages?_fields=slug failed, reason: connect ECONNREFUSED 127.0.0.1:8000
This is the code snippet:
export async function getStaticProps() {
const pages = await getPageList()
//(....)
}
If I query this URL using Postman or just copy and paste in the browser, it works seamlessly too.
Any ideas on what's going on?
I'm using create-next-app, Node 16.13.0, Wordpress 5.8.2, PHP 7.4.3 running using local development server (php -S localhost:8000)
Thank you in advance!
This was related to how I was initiating my PHP built-in server. Changing it to php -S 127.0.0.1:8000 instead of localhost:8000 fixed the problem.