通过 http createServer 提供图像



我正在尝试使用 Node.JS 创建一个基本的网络服务器,但在正确提供图像时遇到了问题。

var server = http.createServer(function (request, response){
if(request.url === '/') {
fs.readFile('public/index.html', 'utf8', function(errors, contents){
response.write(contents); 
response.end();
});
} else {
fs.readFile("public" + request.url, 'utf8', function(errors, contents){
if (!errors) {
response.end(contents);
} else {
console.log('Failed to read file: /public' + request.url);
response.writeHead(404);
response.end();
}
});
}
});

一切正常,除了如果您去查看它尝试下载的图像(我相信它已损坏 - 无法打开它(,这不是我想要的,我希望图像在浏览器中正确提供(而不是通过标签(

奖励点:我需要能够正确给出正确的标头(我只需要一个switch语句并通过它设置它们吗?(,因为chrome发出警告

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost/css.css".

你可以使用 expressjs : http://expressjs.com/

const express = require('express')
const app = express()
app.get('/', (req, res) => res.sendFile('public/index.html'))
app.use(express.static('public'))
app.listen(8080, () => console.log('Example app listening on port 8080!'))

铌:

您的代码不安全:"public" + request.url.您的用户可以获取服务器的所有文件:fs.readFileSync("public/../../../README.txt");

您将在父文件夹上收到错误。

错误:ENOENT:没有这样的文件或目录,请打开"C:\README.txt"。

最新更新