741090
相关说明
本人最近弄了个业余项目,项目目录结构如下图所示:

根目录有 frontend 和 backend,其中 frontend 是Vue构建的网页,frontend/dist 文件夹是生产环境所需的文件,即npm run build后的产物。backend 就是项目后端代码部分,其中 backend/index.js 是入口文件,在里面创建了一个HTTP 服务器。
问题之处
在backend/index.js创建了HTTP服务,在浏览器地址栏输入http://localhost:8080/index.html这个地址预期效果就是:服务端就会返回frontend/dist/index.html资源,同时frontend/dist/index.html有相关css和js链接,就会下载下来然后渲染页面。但实际情况就是网页是空白,但在chrome devtool 的network调试监控没有报出错误。然后我使用postman调试相关链接,都是可以返回对应的文件。
相关代码:
http.createServer(function (request, response) {
let url = request.url;
console.log(url);
let ext, filePath, contentType;
ext = path.extname(url);
ext = ext ? ext.slice(1) : 'unknown';
contentType = MINE[ext];
let contentTypeHeader = {
"Content-Type": contentType
};
if (url.indexOf('/search?') !== -1) {
...
...
} else if (url === '/robots.txt' || url === '/favicon.ico') {
response.writeHead(200, contentTypeHeader);
let readStream = fs.createReadStream(__dirname + url, 'utf8');
readStream.pipe(response);
} else {
let tempPath = path.join('frontend/dist',url);
let root = path.resolve(__dirname,'..');
filePath = path.join(root, tempPath);
console.log(filePath);
response.writeHead(200, contentTypeHeader);
let readStream = fs.createReadStream(filePath, 'utf8');
readStream.pipe(response);
}
}).listen(8080);
const MINE = {
"css": "text/css",
"js": "text/javascript",
"html": "text/html",
"ico": "application/octet-stream",
"txt": "text/plain",
"ttf": "application/octet-stream"
};
console.log("The server is running at port 8080");
chrome devtool:

postman 调试:
