Docs
Routing
Data Fetching
Data Fetching
ERROR
snatcher
has been deprecated since
3.0
.
Since node version v17.5.0
you can use fetch()
without any installation. If node version is below v17.5.0
, install libraries such
as node-fetch
.
middlewares/fetch.ts
import { Middleware, ZelyRequest } from 'zely';
// If you are using typescript, you have to extend `zely.ZelyRequest`.
declare module 'zely' {
interface ZelyRequest {
fetch(url: string, options?: any): Promise<Response>;
}
}
export const Fetch: Middleware = (req, res, next) => {
// @ts-expect-error
req.fetch = (url: string, options: any) => {
return fetch(new URL(url, `http://${req.headers.host as string}`), options);
};
next();
};
Then register middleware in the config file.
Now you can fetch data!
Typescript
import type { PageHandler } from 'zely';
export default [
GET((ctx) => {
const res = await ctx.request.fetch('/api/hello/');
const data = await res.text();
// ...
}),
] satisfies PageHandler[];