Open juicecultus opened 4 years ago
I am getting this error too. I was able to fix it by adding `typeof window === 'undefined' to the conditional expression with writeHead. Now it looks like this:
if (!response.ok && typeof window === 'undefined') {
res.writeHead(302, { Location: '/notes' })
res.end()
return {props: {}}
}
I am honestly now positive why you need this though. @juicecultus
Instead of strict equality (===) operator use Object,is() and le me know!
I had a similar issue, but I was trying to do all with ts. When I convert all to js everything was working as should be
Can anyone explain what exactly is happening here? This seems to cover intricacies of next.js and server responses.
Having the same error. However, if I log params as the first line of getServerSideProps, the function works. Some kind of timing issue where params is not ready when fetch tries to call it, maybe?
export async function getServerSideProps({params, req, res}) {
console.log(params)
const response = await fetch(`http://localhost:3000/api/note/${params.id}`)
if (!response.ok) {
res.writeHead(302, { Location: '/notes' })
res.end()
return {props: {}}
}
const {data} = await response.json()
if (data) {
return {
props: {note: data}
}
}
}```
try this it worked for me
export async function getServerSideProps({ params, req, res }) {
const response = await fetch(http://localhost:3000/api/note/${params.id}
);
if (!response.ok) { return res.writeHead(302, { Location: "/notes" }).end(); }
const { data } = await response.json();
if (data) { return { props: { note: data }, }; } }
Hi Scott @Hendrixer
When I fetch one note in /pages/notes/[id].js the app crashes with the follwoing error:
This is my code for /pages/notes/[id].js:
NOTE: only difference I have from your repo is named exports, my API is at API/notes & my components and data are in root.
A console.log(response) shows:
Steps to trigger the error - follow this path: 1) yarn dev -- OK 2) go to localhost:3000 -- OK 3) click Notes in Nav bar -- OK 4) click any Note -- error (status 404 - not found)
Steps to avoid error: 1) yarn dev -- OK 2) go to localhost: 3000 -- OK 3) go to http://localhost:3000/api/notes/{id from step 4 above} But as soon as you click Notes in Nav bar then you're in trouble again.
Looks like new IDs are generated and somehow headers cannot be updated anymore.