简答
完全使用HTML绕过,你也可以简单地服务于音频文件,而不是Picture.html:
fs.readFile("./audiofile.mp3", function(error, data) {
if (error) {
response.writeHead(404);
} else {
response.writeHead(200, { "Content-Type": "audio/mpeg"});
response.end(data, 'utf-8');
}
});
注: 你将不得不更换文件名audiofile.mp3和内容类型audio/mpeg为您要发送的文件的适当值。
更好的答案:
HTTP模块是相当级别的低,如果你正在学习过于复杂。
您可以使用npm install express --save命令将express.js安装到您的项目中。
与表达你的代码可以简化为:
const express = require('express');
const app = express();
const port = 80;
app.get('/', (request, response) => {
response.sendFile(__dirname + '/Picture.html');
});
// Anything put in the public folder is available to the world!
app.use(express.static(__dirname + '/public'));
app.listen(port,() => {
console.log(`Listening on port: ${port}`)
});
那么你就必须将所有的文件到您的项目目录下名为“公共”文件夹,你可以从HTML调用它们!