Next13 fetch to localhost:8000 does not work
Somehow the fetch from next13 doesnt work with Django on localhost:8001.
I get the following error:
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:7188:34)
at node:internal/deps/undici/undici:7516:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: Error: [object Object]
at makeNetworkError (node:internal/deps/undici/undici:6317:51)
at httpNetworkFetch (node:internal/deps/undici/undici:7810:16)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async httpNetworkOrCacheFetch (node:internal/deps/undici/undici:7703:33)
at async httpFetch (node:internal/deps/undici/undici:7557:37)
at async schemeFetch (node:internal/deps/undici/undici:7489:18)
at async node:internal/deps/undici/undici:7342:20
at async mainFetch (node:internal/deps/undici/undici:7338:20) {
[cause]: undefined
}
}
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:7188:34)
at node:internal/deps/undici/undici:7516:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
digest: '1117663215'
with this code:
import './globals.css'
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
// const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' });
const data = await fetch(`http://localhost:8001/board/`, {
method: 'GET', headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
redirect: 'follow',
cache: 'force-cache'
});
console.log(data)
return (
<html lang="en">
<head />
<body>
<h1></h1>
<div>{children}</div>
</body>
</html>
)
}
Fetching from any other public api works. CORS is enabled and CORS_ORIGIN_ALLOW_ALL = True is set in the Django settings.py
Any idea how I can fix this?
Thanks
Ok I solved it myself
For who are running into the same error here is my solution: you need to replace the localhost with 127.0.0.1 Somehow nextjs doesn't like to fetch data from localhost...
Please find the correct code below:
import './globals.css'
export default async function RootLayout({
children,
}: {
children: React.ReactNode
}) {
// const data = await fetch(`https://dummyjson.com/products/1`, { cache: 'force-cache' });
const data = await fetch(`http://127.0.0.1:8001/board/`, {
method: 'GET', headers: {
'Accept': 'application/json',
"Content-Type": "application/json"
},
redirect: 'follow',
cache: 'force-cache'
});
console.log(data)
return (
<html lang="en">
<head />
<body>
<h1></h1>
<div>{children}</div>
</body>
</html>
)
}