You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Koa替代Express开发时如何将Axios请求结果返回到浏览器

问题根因
  • 异步逻辑未等待:Axios请求是异步操作,原代码未等待请求返回就结束了Koa的请求处理流程。未注释末尾三行时,Axios还未返回结果就已经把空的axiosResponse赋值给ctx.body返回;注释后则根本没来得及给ctx.body赋值,Koa默认返回404。
  • koa-router方法调用错误:router.allowedMethods是方法,需加括号调用,原代码漏写括号会导致路由规则匹配异常。
  • 第三方接口参数拼接错误:OMDb接口的查询参数缺失参数名,原URL中apikey=<myApiKey>=${myName}的写法错误,需要在apikey后补充&t=(按影视标题搜索的参数名)。
修复后代码
const Koa = require('koa');
const KoaRouter = require('koa-router');
const axios = require('axios');

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

// 路由回调改为async函数支持await
router.get('/:name', async (ctx, next) => {
    const myName = encodeURI(ctx.request.params.name);
    try {
        // 等待axios请求返回再赋值ctx.body
        const response = await axios.get(`https://www.omdbapi.com/?apikey=<myApiKey>&t=${myName}`);
        ctx.body = response.data;
    } catch (error) {
        console.log(error);
        ctx.body = {
            code: 500,
            msg: '请求第三方接口失败'
        }
    }
});

// allowedMethods补括号调用
app.use(router.routes()).use(router.allowedMethods());

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

注意:代码中的<myApiKey>需要替换为你自己申请的OMDb接口实际密钥。

验证

启动服务后访问http://localhost:3000/star%20wars,即可正常拿到接口返回的影视数据。

内容的提问来源于stack exchange,提问作者Rafael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:06:02