express4.*res.sendFile()的写法用koa2怎么实现?

查看:283
本文介绍了express4.*res.sendFile()的写法用koa2怎么实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

koa2怎么指定html跳转首页?

在express4.*是这样实现的:

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
    res.sendFile(__dirname+'/index.html');
});
http.listen(5566, function(){
    console.log('listening on *:5566');
});

变成koa2 应该怎么写? 网上的教程都是只有这样:

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

app.use(async (ctx, next) => {
    await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2! to cmy</h1>';
});

app.listen(9000);
console.log('app started at port 9000...');

解决方案

读取文件直接fs.readFile,将返回文件赋给ctx.body,不就行了!注意设置ctx.type为html,否则就是下载了!

router.get('/', async(ctx, next) => {
  var htmlFile = await (new Promise(function(resolve, reject){
      fs.readFile('./t.html', (err, data) => {
        if (err){
          reject(err);
        }else{
          resolve(data);
        }
      });
  }))
  ctx.type = 'html';
  ctx.body = htmlFile;
});


//还可以是用ReadStream,更简单
router.get('/',(ctx, next) => {
  ctx.type = 'html';
  ctx.body = fs.createReadStream('./t.html');
});

这篇关于express4.*res.sendFile()的写法用koa2怎么实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆