CNode

关于KOA做一个简单的静态服务器

Gguotingchaopr发布于13 年前最后回复13 年前11 回复24589 浏览0 收藏

为什么读取文件以后设置总是报错

this.body = data

**Can't set headers after they are sent. **

查看回复

回复 (11)

给个完整点的代码

Y
youxiachai#2·13 年前

res 调了两次...

G
guotingchaopr#3·13 年前
引用 coderhaoxin__legacy_52c234678a716e0b15b7b6c7给个完整点的代码
var _this = this; 
fs.readFile(path,'binary',function(err,data){
 console.log(data);
 if(err)console.log(err)
else{
  _this.response.type = 'text/html; charset=utf-8';
  _this.response.writeHead(200, 'SUP?', { 'content-type': 'html' });
  _this.render(path);
   _this.response.body = data; //就是这里
 }
});
G
guotingchaopr#4·13 年前
引用 coderhaoxin__legacy_52c234678a716e0b15b7b6c7给个完整点的代码

//_this.render(path) 这个是注释掉的

G
guotingchaopr#5·13 年前
引用 youxiachaires 调了两次...

我只要把 this.body = data. 换成 随便个字符就好了。

X
xieren58#6·13 年前
引用 youxiachaires 调了两次...

@guotingchaopr koa-static 可以么?

koa-static, koa-static-cache可以满足一般需求了吧。

至于报错原因,是因为在回调结束前就已经结束响应了。 在generator内部,你需要使用yield而非回调

var koa = require('koa')
var app = koa()
var fs  = require('co-fs')

app.use(function* (){
 this.body = yield fs.readFile('./app.js', 'utf8')
})

app.listen(3000)

你可以试试下面的测试代码 取消注释可以得到响应,否则404

var koa = require('koa')
var app = koa()
var fs = require('fs')

app.use(function* (){
 fs.readFile('./app.js', 'utf8', function (e, data) {
  console.log(data)
  this.body = data
 })
 // this.body = 'hello'
})

app.listen(3000)

D
dead-horse#8·13 年前

既然用了koa, 就尽量别写回调的代码了...

G
guotingchaopr#9·13 年前
引用 dead-horse既然用了koa, 就尽量别写回调的代码了...

哦 好的 初学这个框架以后会注意了

G
guotingchaopr#11·13 年前
引用 youxiachaires 调了两次...

@xieren58 嗯 我明白了。是我写的方法不对

参与回复
登录后即可参与回复。登录