我是一个节点,网页开发和编程初学者以下‘获得编程与Node.js’由乔纳森韦克斯勒。我已经完成了关于香草节点路由的部分的结尾部分,下面是main.js中的代码:
http = require("http"),
httpStatusCodes = require("http-status-codes"),
fs = require("fs"); // This is a node js core module which interacts with the filesystem on behalf of the app.
(router = require("./router")),
(plainTextContentType = {
"Content-Type": "text/plain",
}),
(htmlContentType = {
"Content-Type": "text/html",
}),
(pngContentType = {
"Content-Type": "image/png",
}),
(customReadFile = (file, res) => {
fs.readFile(`./${file}`, (errors, data) => {
if (errors) {
console.log("Error reading the file...");
}
res.end(data);
});
});
router.get("/", (req, res) => {
res.writeHead(httpStatusCodes.OK, plainTextContentType);
res.end("INDEX");
});
router.get("/index.html", (req, res) => {
res.writeHead(httpStatusCodes.OK, htmlContentType);
customReadFile("views/index.html", res);
});
router.get("/image.png", (req, res) => {
res.writeHead(httpStatusCodes.OK, pngContentType);
customReadFile("public/images/image.png");
});
router.post("/", (req, res) => {
res.writeHead(httpStatusCodes.OK, plainTextContentType);
res.end("POSTED");
});
http.createServer(router.handle).listen(3000);
console.log(`The server is listening on port number: ${port}`);它可以很好地加载/index.html文件,但是当我尝试加载/image.png (存储在正确的文件夹中,public/images/image.png)时,它总是与错误消息TypeError:无法读取未定义的属性'end‘一起崩溃。
无论我使用什么图像,都会发生这种情况,如果我将图像移动到另一个文件夹(如视图),也会发生这种情况。我还尝试编写res.write(数据);res.end(),但也没有效果。我也尝试在fs.readFile中使用异步函数,但我不认为这是问题所在,因为如果我正确理解,fs.readFile本身应该在函数内同步执行。
编辑
router.js的代码,以防有帮助:
const httpStatus = require("http-status-codes"),
htmlContentType = {
"Content-Type": "text/html",
},
routes = {
GET: {
"/info": (req, res) => {
res.writeHead(httpStatus.OK, {
"Content-Type": "text/plain",
});
res.end("Welcome to the Info Page!");
},
},
POST: {},
};
exports.handle = (req, res) => {
try {
if (routes[req.method][req.url]) {
routes[req.method][req.url](req, res);
} else {
res.writeHead(httpStatus.NOT_FOUND, htmlContentType);
res.end("<h1>No such file exists</h1>");
}
} catch (ex) {
console.log("error: " + ex);
}
};
exports.get = (url, action) => {
routes["GET"][url] = action;
};
exports.post = (url, action) => {
routes["POST"][url] = action;
};发布于 2020-04-06 12:35:33
您必须将res对象作为第二个参数传递给您的customReadFile函数,以使其工作。你所拥有的:
router.get("/image.png", (req, res) => {
res.writeHead(httpStatusCodes.OK, pngContentType);
customReadFile("public/images/image.png"); // <-- 2nd arg missing
});你想要的是:
router.get("/image.png", (req, res) => {
res.writeHead(httpStatusCodes.OK, pngContentType);
customReadFile("public/images/image.png", res); // <-- 2nd arg added
});https://stackoverflow.com/questions/61059854
复制相似问题