大家看一下代码,有什么问题?


错误信息:


 Server start at port 3000
/home/dell/project/chat/server.js:9
  res.writeHead(404,{'Content-Type':'text/plain'})
      ^

TypeError: res.writeHead is not a function
    at send404 (/home/dell/project/chat/server.js:9:7)
    at /home/dell/project/chat/server.js:41:9
    at FSReqWrap.cb [as oncomplete] (fs.js:212:19)

代码:


 var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {}; //cache是用来缓存文件中的数据的对象

//发送错误信息
function send404(res) {
  res.writeHead(404,{'Content-Type':'text/plain'})
  res.write('Error 404: resoure not found.');
  res.end();
}

//发送文件
function sendFile(res, filePath, fileContents) {
  res.writeHead(200, {
    'Content-Type': mime.lookup(path.basename(filePath)) //path的basename方法获取路径的最后一部分,通过后缀名指定mime类型
  });
  res.end(fileContents);
}

//提供静态文件服务
function serveStatic(res, cache, absPath) {

  if (cache[absPath]) {
    sendFile(res, absPath, cache[absPath]);
  } else {
    //判断文件是否存在
    fs.exists(absPath, function (exists) {
      if (exists) {
        //读取文件
        fs.readFile(absPath, function (err, data) {
          if (err) {
            send404(res);
          } else {
            cache[absPath] = data;
            sendFile(res, absPath, data);
          }
        });
      } else {
        send404(res);
      }
    });
  }
}
//创建http服务器
var server = http.createServer(function (res, req) {
  var filePath = false;

  if (req.url == '/') {
    filePath = 'public/index.html'; //返回静态的html文件
  } else {
    filePath = 'publc' + req.url; //将url转换为文件的相对路径
  }

  var absPath = './' + filePath;
  serveStatic(res, cache, absPath);
});

//监听3000端口
server.listen(3000, function () {
  console.log("Server start at port 3000");
});

node.js JavaScript

纯洁得像Y贼 8 years, 6 months ago

res.writeHead 不是一个方法。错误提示很明显了。

逆袭D软妹 answered 8 years, 6 months ago

req,res两个参数位置写反了,req在前

moses answered 8 years, 6 months ago

Your Answer