请求JSON文件时获取响应为空';s含量| koa2
我是koa2的新手,我试图用koa2获取JSON文件的内容请求JSON文件时获取响应为空';s含量| koa2,json,node.js,koa,koa2,Json,Node.js,Koa,Koa2,我是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", "da
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;
致:
您应该现在就获得内容。Koa本身不支持路由,只支持中间件,您需要有一个路由器中间件,试试看 你的应用程序看起来像
const route = require('koa-route')
app.use(route.get('/list', ctx => {
// Route handling logic
});
还要注意,
ctx.get
是ctx.request.get
的别名,它返回头信息 这可能不是Koa做事的方式,但这正是我尝试并为我工作的方式(适用于像我这样的noobs的完整代码):
和膝关节炎一样,KOA本身不支持路由选择。您需要使用一些路由中间件。
您已经定义了一个中间件,但是处理/list
路由路径的代码在哪里?JSON文件托管在哪里,在您的公共目录中还是在另一个域中?难道不是ctx.get()
只是ctx.request.get()的别名吗?我现在很好奇:-你测试过这个代码吗?我仍然得到一个空洞的回答。试试我的
const route = require('koa-route')
app.use(route.get('/list', ctx => {
// Route handling logic
});
// 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);