【发布时间】:2016-08-27 18:12:43
【问题描述】:
看,我正在使用 Node(和 TS btw)进行培训,并尝试使用多个请求/响应选项做一个简单的服务器。但是我有一个问题,如果不使用 Express,我不知道如何解决(至少现在我不想使用它)。
我有一个请求图像文件的 HTML 文件。在 IDE 中,一切看起来都可以正常工作,但是当服务器运行时,找不到映像。原因很明显:HTML 发出了一个服务器不知道如何处理的请求。问题是,我认为该文档可以引用其他文件而无需与服务器对话。
对于我的问题,什么是优雅且有效的解决方案?
提前致谢。
import * as http from 'http'
import * as fs from 'fs'
fs.readFile('doc/kmCNHkq.jpg', function (err, data) {
let binaryimg = new Buffer(data).toString('base64');
if (err) throw err;
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'});
res.end(data);
console.log("Delivered the jpeg");
}).listen(8000);
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(binaryimg);
console.log("Delivered base64 string");
}).listen(8124);
console.log("Unless bug, both servers are listening");
});
fs.readFile('doc/index.html', function(err, data) {
http.createServer(function(req,res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data)
}).listen(80);
console.log("HTML server is running")
})
(main.ts; 目标 ES6)
<html>
<head>
</head>
<body>
<img src="doc/kmCNHkq.jpg"/>
</body>
</html>
(index.html)
观察:我以前将 HTML 文件放在“../doc/”中,将资源放在“../img/”中,但似乎 HTML 使用相对路径,所以我将图像复制到 HTML 的文件夹中。如果解决方案也成功了,我可以将资源留在他们各自的文件夹中,我们将不胜感激。
@编辑: 现在我正在使用这个 switch/case 请求处理程序。按预期工作,HTML 对图像的请求被解释为正常请求(可能最终无法很好地缩放,idk,但搞砸了)。非常感谢!
import * as http from 'http'
import * as fs from 'fs'
var stream: fs.ReadStream,
folder = __dirname.substr(0, __dirname.length - 3);
http.createServer(function(req,res) {
switch (req.url){
case('/jpeg'):
stream = fs.createReadStream(folder + 'img/kmCNHkq.jpg');
stream.pipe(res);
console.log("Delivering the jpeg");
break;
case('/base64'):
fs.readFile('img/kmCNHkq.jpg', function (err, data) {
let img64 = new Buffer(data).toString('base64');
if (err) throw err;
res.end(img64);
console.log("Delivered base64 string");
})
break;
case('/html'):
stream = fs.createReadStream(folder + 'doc/index.html');
stream.pipe(res);
console.log("Sending the docs");
break;
default:
console.log("Shit happens");
}
}).listen(80)
(main.ts)
<html>
<body>
<img src="jpeg"/>
</body>
</html>
(index.html)
【问题讨论】:
标签: html node.js path typescript server