koa2获取图片并返回,设置静态文件目录,访问本地文件

const Koa = require( 'koa');
const app = new Koa();

// const path = require('path');
// const fs = require('fs');

// // x-response-time

// app.use(async (ctx, next) => {
// const start = Date.now();
// await next();
// const ms = Date.now() - start;
// ctx.set('X-Response-Time', `${ms}ms`);
// console.log(1, path);
// });

// // logger

// app.use(async (ctx, next) => {
// const start = Date.now();
// await next();
// const ms = Date.now() - start;
// console.log(`${ctx.method} ${ctx.url} - ${ms}`);
// console.log(2, path);
// });

// // response

// app.use(async ctx => {
// ctx.body = 'hello world!';
// });
const router = require( 'koa-router')();
const request = require( 'request');

router. get( '/', async function( ctx, next) {
await new Promise( function( resolve, reject) {
var req = request({
method: 'GET',
encoding: null,
// uri: 'http://images5.fanpop.com/image/photos/30900000/beautiful-pic-different-beautiful-pictures-30958249-1600-1200.jpg'
uri: 'http://seopic.699pic.com/photo/40014/3406.jpg_wh1200.jpg'
}, function( err, response, body) {
if ( err) {
return reject( err);
}
resolve( body);
});
}). then(( body) => {
ctx. status = 200;
ctx. type = 'jpg';
console. log( Buffer. isBuffer( body));
ctx. length = Buffer. byteLength( body);
ctx. body = body;
}). catch(( err) => {
console. error( err);
});
});
// 静态文件目录
app. use( require( 'koa-static')( __dirname));

app. use( router. routes());
app. listen( 8080);

猜你喜欢

转载自blog.csdn.net/onlyliii/article/details/80417705
今日推荐