【问题标题】:Showing the result of an axios request in the browser with Koa使用 Koa 在浏览器中显示 axios 请求的结果
【发布时间】:2021-12-09 07:07:53
【问题描述】:

我使用的是 KOA 而不是 express

如何向浏览器显示 axios 结果数据

这是我的代码:

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...'));

通过输入“http://localhost:3000/star%20wars”它返回“未找到”,但如果我取消注释端点的最后 3 行,它会找到它(但返回一个空结果,当然)

拉斐尔

【问题讨论】:

    标签: axios koa koa-router ctx


    【解决方案1】:

    我找到了解决办法:

    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;
        }
    );
    

    【讨论】:

      【解决方案2】:

      更简单的解决方案

      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;
      });
      

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        • 2018-06-01
        • 2022-01-04
        • 2020-01-13
        • 2019-08-26
        • 2018-12-15
        相关资源
        最近更新 更多