Cannot fetch in Server Component of App Router
Answered
mta posted this in #help-forum
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
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
@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
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
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 Boundarythrow 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
not working man 😦
mtaOP
so i have an answer for this question
mtaOP
currentlly im using wsl so it cannot fetch localhost
Answer