【问题标题】:Empty GET response on requesting JSON file's content | koa2请求 JSON 文件内容的空 GET 响应 | koa2
【发布时间】:2018-05-07 14:51:21
【问题描述】:

我是 koa2 的新手,我正在尝试使用 koa2 获取 JSON 文件的内容

app.use( async ( ctx ) => { 
  let url = ctx.request.url;
  if (url == "list") {
      let res = ctx.request.get('http://domain/hello.json');
      ctx.body = res.body;
  }
})

JSON 文件 hello.json 如下所示:

{"da": "1212", "dad": "12addsf12"}

我希望路由/list 返回hello.json 的内容,但是响应为空。我该怎么办?

更新: 更改以下代码行:

 let res = ctx.request.get('http://domain/hello.json');
 ctx.body = res.body;

到:

 let res = ctx.get('http://domain/hello.json');
 ctx.body = res;

你现在应该得到内容了。

【问题讨论】:

  • 你已经定义了一个中间件,但是处理/list路由路径的代码在哪里呢? JSON 文件托管在您的公共目录中还是其他域中?
  • ctx.get() 不只是ctx.request.get() 的别名吗?我现在很好奇:-o

标签: json node.js koa koa2


【解决方案1】:

Koa 本身不支持路由,只有中间件,需要有路由中间件,试试koa-router

你的应用看起来像

const route = require('koa-route')

app.use(route.get('/list', ctx => {
    // Route handling logic
});

还要注意ctx.getctx.request.get 的别名,它返回标头信息。

【讨论】:

  • 你测试过这段代码吗?我仍然得到一个空洞的回应。试试我的example
【解决方案2】:

这可能不是 Koa 的做事方式,但这是我为我尝试和工作的方式(像我这样的菜鸟的完整代码):

// jshint ignore: start
const koa2 = require("koa2");
const router = require('koa-simple-router');
const app = new koa2();
const request = require('request-promise-native');

// response
app.use(router(_ => {
    _.get('/list', async (ctx) => {
        const options = {
            method: 'GET',
            uri: 'http://www.mocky.io/v2/5af077a1310000540096c672'
        }
        await request(options, function (error, response, body) {
            // I am leaving out error handling on purpose, 
            // for brevity's sake. You must in your code.
            ctx.body = body;
        })
    });
}));

app.listen(3000);

而且,就像J Pichardo's answer 指出的那样,Koa 本身不支持路由。你需要使用一些路由中间件。

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2014-09-01
    • 1970-01-01
    • 2022-10-09
    • 2020-11-19
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多