0

In my "/yourPage" route, my handler is trying to fetch "/api/joke" from my local database. I get "URL not found" error. Since Fresh is server rendered, I'd like to get all the data I need when loading the first time.

This works fine when fetching after initial load (like with a button). As per its documentation, it should work fine, and does for any API that is not in its own repository.

Any way I can make this work? Am I thinking of this the wrong way?

The fetch inside my handler: routes/yourPage.ts

export const handler: Handlers = {
async GET(req, ctx) {
    const joke = await getJokes()
    return ctx.render(joke);
},

};

/routes/api/joke.ts

const JOKES = [
  "Why do Java developers often wear glasses? They can't C#.",
  "A SQL query walks into a bar, goes up to two tables and says “can I join you?”",

];

export const handler = (_req: Request, _ctx: HandlerContext): Response => {
  const randomIndex = Math.floor(Math.random() * JOKES.length);
  const body = JOKES[randomIndex];
  return new Response(body);
};
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

0

Pretty old post, but this is the first StackOverflow Google result when you try to search for API calling in Fresh Framework.

I am assuming you imported inside routes/yourPage.ts the handler from /routes/api/joke.ts as this:

import { handler as getJokes } from "./api/joke.ts";

Inside routes/yourPage.ts you also have to extract the text/json from the response before using it:

export const handler: Handlers = {
  async GET(_req, _ctx) {
    const response = getJokes(_req, _ctx);
    const jokeText = await response.text();
    return _ctx.render(jokeText);
  },
};

Then you can use the response in your page as:

export default function Home({ data }: PageProps) { //...

Documentation here:
https://fresh.deno.dev/docs/getting-started/fetching-data

Cosmin
  • 1
  • 1