Rafael
Rafael

Reputation: 2729

Showing the result of an axios request in the browser with Koa

I’m using KOA instead of express

How can I show an axios result data to the browser

Here is my code:

const Koa = require('Koa');
const KoaRouter = require('koa-router');
var axios = require('axios');

const app = new Koa();
const router = new KoaRouter();

router.get('/:name', (ctx, next) => {
    let myName = encodeURI(ctx.request.params.name);
    let axiosResponse = {};
    axios
        .get(`https://www.omdbapi.com/?apikey=<myApiKey>=${myName}`)
        .then((response) => {
            ctx.body = response.data;
            axiosResponse  = response.data
        })
        .catch((error) => {
            console.log(error);
        });
    // ctx.body = {
    //    data: axiosResponse
    // };
});

app.use(router.routes()).use(router.allowedMethods);

app.listen(3000, () => console.log('server Started...'));

By typing "http://localhost:3000/star%20wars" it returns "not found", but if I uncomment the last 3 lines of the endpoint, it finds it (but returns an empty result, of course)

Rafael

Upvotes: 0

Views: 828

Answers (2)

Evert
Evert

Reputation: 99776

A simpler solution

router.get('/:name', async (ctx, next) => {
  const myName = encodeURI(ctx.request.params.name);
  const response = await axios
     .get(`https://www.omdbapi.com/?apikey=<myApiKey>=${myName}`)
  ctx.body = response.data;
});

Upvotes: 1

Rafael
Rafael

Reputation: 2729

I found the solution:

router.get(
    '/:name',
    (ctx, next) => {
        let myName = encodeURI(ctx.request.params.name);
        return axios
            .get(`https://www.omdbapi.com/?apikey=<myApiKey>&t=${myName}`)
            .then(function (response) {
                ctx.movie = response.data;
                next();
            });
    },
    (ctx) => {
        ctx.body = ctx.movie;
    }
);

Upvotes: 0

Related Questions