问题描述
使用以下Node.js program,我尝试在端口号test.png
上托管一个名为3000
的映像。
var info = 'Node server for a test';
var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');
var dir = path.join(__dirname,'public');
var mime = {
html: 'text/html',txt: 'text/plain',css: 'text/css',gif: 'image/gif',jpg: 'image/jpeg',png: 'image/png',svg: 'image/svg+xml',js: 'application/javascript'
};
app.get('*',function (req,res) {
var file = path.join(dir,req.path.replace(/\/$/,'/index.html'));
if (file.indexOf(dir + path.sep) !== 0) {
return res.status(403).end('Forbidden');
}
var type = mime[path.extname(file).slice(1)] || 'text/plain';
var s = fs.createReadStream(file);
s.on('open',function () {
res.set('Content-Type',type);
s.pipe(res);
});
s.on('error','text/plain');
res.status(404).end('Not found');
});
});
app.listen(3000,function () {
console.log('Listening on http://localhost:3000/');
});
console.log(info); var info = 'Node server for a test';
var path = require('path');
var express = require('express');
var app = express();
var fs = require('fs');
var dir = path.join(__dirname,function () {
console.log('Listening on http://localhost:3000/');
});
console.log(info);
test.png
位于/Users/myusername/testhost
。
当我在Chrome上打开http://localhost:3000/test.png
时,它只是在浏览器上抱怨“无法获取/test.png”。即使我也提供图像的完整路径,它也不起作用。我正在macOS上运行它。
问题:
当网络服务器在macOS或Linux上运行时,以上程序是否正确?如何将映像从macOS服务器存储到在浏览器或应用程序上运行的程序?
解决方法
要提供静态文件(例如图像,CSS文件和javaScript文件),请在express中使用express.static
内置的中间件功能。
例如,使用以下代码在名为public的目录中提供图像,CSS文件和JavaScript文件:
app.use(express.static('public'))
现在,您可以将test.png文件放在公共目录中,并通过以下方式加载它:
http://localhost:3000/test.png