Failed to parse URL. reading data from API in getServerSideProps()
Unanswered
Chinese Alligator posted this in #help-forum
Chinese AlligatorOP
I'm trying to get values from my API from
from code:
what am i missing?
getServerSideProps() but I'm getting the error:- error Error [TypeError]: Failed to parse URL from /api/read_article?id=1
at Object.fetch (node:internal/deps/undici/undici:11118:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async fetchArticleFromDatabase (webpack-internal:///./pages/articles/[id].tsx:40:22)
at async getServerSideProps (webpack-internal:///./pages/articles/[id].tsx:31:25) {
digest: undefined
}from code:
import { GetServerSideProps, NextPage, NextPageContext } from 'next';
import IArticleResult from '@interfaces/IArticleResult';
import IArticle from '@/interfaces/IArticle';
interface PropductProps {
product: IArticleResult;
}
const Index = (props: PropductProps) => {
return(<div>the title is {props.product.result![0].title}</div>)
}
export const getServerSideProps: GetServerSideProps<{product: IArticleResult}> = async (context) => {
const { params } = context;
const id: string = Array.isArray(params?.id) ? params!.id[0] : (params?.id || "");
console.log('getServerSideProps says, params = ', params);
console.log('getServerSideProps says id = ', id);
if(id.length === 0) {
return {
notFound: true
}
}
// Fetch the article data from the database using the ID
const articleData: IArticleResult = await fetchArticleFromDatabase(id);
// Pass the article data as props to the page component
return {
props: {
product: articleData,
},
};
};
async function fetchArticleFromDatabase(id: string): Promise<IArticleResult> {
const response = await fetch(`/api/read_article?id=${id}`);
const data = await response.json();
console.log('data = ', data);
return data;
}
export default Index;what am i missing?
2 Replies
Chinese AlligatorOP
just using the full URL instead of relative path did work. Now how do I get the full URL automatic/dynamically instead of hard-code it? what's commonly used? i'm using below code by now:
const serverProtocol = req.headers['x-forwarded-proto'] || 'http';
const serverHost = req.headers.host || '';
const serverUrl = `${serverProtocol}://${serverHost}`;Chinese AlligatorOP
i just used https://www.npmjs.com/package/next-absolute-url and did the job well