Issue
I use SWR to fetch data but get the error of repeating the default path of nextjs
http://localhost:3000/127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5
tsx:
'use client'
import useSWR from "swr";
import HomeOutstanding from "@/components/partials/home/HomeOutstanding ";
const fetcher = (url: string) => fetch(url).then((res) => res.json());
const API_POST_POPULAR = process.env.API_URL + ':' + process.env.API_PORT + '/api/posts/get-five-post-popular?skip=0&limit=5'
export default function Home() {
const { data, error, isLoading} = useSWR(
API_POST_POPULAR,
fetcher
)
if (isLoading) {
return <div>Loading...</div>
}
if (error) {
return <div>Failed to api</div>
}
if (!data) {
return <div>Loading</div>
}
.env:
API_URL=127.0.0.1
API_PORT=8000
How to get the correct path http://127.0.0.1:8000/api/posts/get-five-post-popular?skip=0&limit=5 . Thanks everyone
Solution
I think you're missing the "http://" in front of the url. Without it fetch think's the request should come to localhost
Try something like.
const url = `http://${process.env.API_URL}:${process.env.API_PORT}/api/posts/get-five-post-popular?skip=0&limit=5`
or just include it in the env variable
API_URL='http://127.0.0.1'
Answered By - KingxMe
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.