javascript - 大家看一下代码,有什么问题?
阿神
阿神 2017-04-10 16:13:30
[JavaScript讨论组]

错误信息:

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");
});

阿神
阿神

闭关修行中......

全部回复(3)
高洛峰

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

天蓬老师

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

迷茫
//创建http服务器
var server = http.createServer(function (res, req) {
  var filePath = false;

你这里的res req 写反了。应该是: function (req, res)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号