Next.js Discord

Discord Forum

404 error while api post

Unanswered
English Foxhound posted this in #help-forum
Open in Discord
English FoxhoundOP
Error adding data: AxiosError: Request failed with status code 404

22 Replies

English FoxhoundOP
@Risky down under
can you share what your request looks like (url and code) and what it is consuiming (ie the endpoint)
English FoxhoundOP
ok
import axios, { Axios } from 'axios';
import React from 'react'
const page = async () => {
const dataToSend =
{
"value1": "dhuvara",
"value2": "Solution",
"value3": "mani"
}

axios.post('http://localhost:3000/pages/api/addpagecontents',dataToSend,
{
headers: {
'Content-Type': 'application/json'
}
})
.catch((error) => {
console.log("-----------------------------------------------------------------------------------------")
console.error('Error adding data:', error);
})
return (
<div>page</div>
)
}

export default page
this my code
can you show a screenshot of your file tree (like side panel of vscode)
English FoxhoundOP
ahh so your using app dir
so 2 problems i see
1. you shouldn't fetch your own apis inside server component https://nextjs-faq.com/fetch-api-in-rsc
2. your api route needs to be in a folder and end with route.ts
English FoxhoundOP
this is my error
yeah because api routes syntax has changed in between app and pages dir
in app dir, you make the file end with route.ts and the folders are the pathname
English FoxhoundOP
to resolve this what should i do now
edit your route file to have the addpagecontents.ts to be inside the folder named addpagecontents and have a file inside it with route.ts
@riský 1. you shouldn't fetch your own apis inside server component https://nextjs-faq.com/fetch-api-in-rsc
but as i said here, you are using server component, so you should either make it client and use fetch or just do the code directly (no unessary requests)
English FoxhoundOP
but excuted same code after the specifing it as client
but facing same error
English FoxhoundOP
Live fire server