Next.js Discord

Discord Forum

Cannot fetch in Server Component of App Router

Answered
mta posted this in #help-forum
Open in Discord
mtaOP
When I create a Home page in App router's page file, when I use fetch to java be it doesn't work and fails to fetch. But when used in a client component, specifically "use client", it works effectively
Answered by mta
currentlly im using wsl so it cannot fetch localhost
View full answer

17 Replies

Netherland Dwarf
It should work the fetch in servrr comp
Barbary Lion
I think you have to wrap it inside a function and use the "use server" directive and await the results
@Barbary Lion I think you have to wrap it inside a function and use the "use server" directive and await the results
mtaOP
it still not work
@Netherland Dwarf It should work the fetch in servrr comp
mtaOP
im trying with "use server" and it not work
Netherland Dwarf
I know that if you use an external api like jsonplaceholder it will work the fetch
So the issue is probably how the request being sent
Im still trying to look into this.
mtaOP
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations with docs like that, and async function getData() {
const res = await fetch('https://api.example.com/...')
// The return value is not serialized
// You can return Date, Map, Set, etc.

if (!res.ok) {
// This will activate the closest error.js Error Boundary
throw new Error('Failed to fetch data')
}

return res.json()
}

export default async function Page() {
const data = await getData()

return <main></main>
} im trying code with function getData() but when i try with this api https://jsonplaceholder.typicode.com/ it working, but when i try with my server java it not work
Netherland Dwarf
In java
Did you put allow origins
127.000.1
I only see localhost allowed
mtaOP
i made it
not working man 😦
mtaOP
so i have an answer for this question
mtaOP
currentlly im using wsl so it cannot fetch localhost
Answer