这是我编写nodejs的第一天。这是一本名为node.js的书的代码示例。这是一本关于如何将node.js编码为初学者的好书。但在1天后,我遇到了一个错误。我已经复制了代码,并尝试了一切,但似乎没有任何工作。这是我无法工作的代码。ServeStatic没有定义 - 纯node.js
我的错误时,试图运行:的ReferenceError:serveStatic没有定义
现在我已经安装了模块和我的文件需要它。 现在我得到一个新的错误:“类型错误:根路径必须是一个字符串”
现在说
类型错误:根路径必须在serveStatic是一个字符串 (/应用/ XAMPP/xamppfiles /htdocs/learningmern/chatapp1/node_modules/serve-static/index.js:44
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {}
// Helper functions
function send404(res){
res.writeHead(404,{"Content-Type":"text/plain"});
res.write("error 4o4");
res.end();
}
function sendFile(res, filePath, fileContents){
res.writeHead(200, {"Content-Type": mime.lookup(path.basename(filePath)) });
res.end(fileContents);
}
function serveCache(res, cache, absPath){
if (cache[absPath]){
readFile(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;
fs.readFile(res, absPath, data);
}
})
} else {
send404(res);
}
})
}
}
//run server
var server = http.createServer(function(req, res){
var filePath = false;
if (req.url == "/"){
filePath = "public/index.html";
} else {
filePath = "public" + req.url;
}
var absPath = "./" + filePath;
serveStatic(res, cache, absPath);
});
server.listen(3000, function(){
console.log("server started at port 3000");
});
感谢
好的,谢谢。现在它说“TypeError:根路径必须是字符串” – PIK123
TypeError:根路径必须是字符串 serveStatic(/Applications/XAMPP/xamppfiles/htdocs/learningmern/chatapp1/node_modules/serve-static/index.js:44 – PIK123
您的书可能会展示如何使用旧版本的serveStatic,请查看https://github.com/expressjs/serve-static获取当前版本的用法,它只应用两个参数,您的示例显示使用console.log调试各种变量,并继续尝试。 – MichaelWClark