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...');
阅读 9k
2 个回答

读取文件直接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');
});
新手上路,请多包涵

可以使用 koa-static 来处理静态文件

const static = require('koa-static')

app.use('/static', static('/source/'))

所有请求 /static 路径,都会被指向 /source 文件夹,注意路径要映射正确

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进