Why does getInitialProps
cause axios to throw an exception? When I call my service method anywhere else it works fine.
export default function JobIndex({ jobPosts }: JobIndexProps) {
return (
<div>
<ul>
{jobPosts.map(jobPost => {
return <li>{jobPost.title}</li>
})}
</ul>
</div>
)
}
JobIndex.getInitialProps = async (context): Promise<JobIndexInitialProps> => {
const jobPosts = await JobPostService.list({ page: 1, perPage: 3 });
return { jobPosts };
}
And this is my service class:
export class JobPostService {
static async list(request: JobPostListRequest): Promise<JobPostListItem[]> {
const response = await axios.get('/api/job-posts', { params: request });
return response.data as JobPostListItem[];
}
}
This the stack trace:
Server Error
Error: Request failed with status code 404
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
createError
file: .../node_modules/axios/lib/core/createError.js (16:15)
settle
file: .../node_modules/axios/lib/core/settle.js (17:12)
IncomingMessage.handleStreamEnd
file: .../node_modules/axios/lib/adapters/http.js (244:11)
IncomingMessage.emit
events.js (327:22)
endReadableNT
_stream_readable.js (1327:12)
processTicksAndRejections
internal/process/task_queues.js (80:21)
Based on HMR's comment, I ended up modifying my service method to include the absolute url with my base url as an environment variable.
export class JobPostService {
static async list(request: JobPostListRequest): Promise<JobPostListItem[]> {
const response = await axios.get(`${process.env.NEXT_PUBLIC_BASE_URL}/api/job-posts`, { params: request });
return response.data as JobPostListItem[];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.