我正在尝试通过nodeJS提供静态文件,并且能够提供图像和html页面,但是当我请求样式表和javascript文件时,请求将保持待处理状态,并且永远不会结束。下面是代码相关部分的摘录,以及网络的屏幕截图。
Network tab in developer tools
Node JS部分:
index.js
"use strict";
const http = require('http');
const requestModule = require('./Modules/Request');
const header = require('./Modules/Header');
const server = http.createServer(function (request, response) {
switch (request.method) {
case 'GET':
requestModule.getRequest(request, response);
break;
case 'POST':
requestModule.postRequest(request, response);
break;
default:
response.writeHead(501, header['plain']);
response.end();
break;
}
});
server.listen(8119);
请求模块
"use strict";
const url = require('url');
const fs = require("fs");
const crypto = require('crypto');
const header = require('./Header').header;
const helper = require('./Helper');
module.exports.getRequest = function (request, response) {
let sentURL = url.parse(request.url, true);
let path = sentURL.pathname;
let content = sentURL.query;
let body = '';
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function () {
switch (path) {
case '/': //THIS PART WORKS
fs.readFile('../Frontend/index.html', function (err, data) {
if (err) throw err;
response.writeHead(200, header['html']);
response.write(data);
response.end();
});
break;
case '/style.css':
fs.readFileSync('../Frontend/style.css', function (err, data) {
if (err) throw err;
response.writeHead(200, header['css']);
response.write(data);
response.end();
});
break;
case '/main.js':
fs.readFileSync('../Frontend/_main.js', function (err, data) {
if (err) throw err;
response.writeHead(200, header['plain']);
response.write(data);
response.end();
});
break;
标题模块:
plain: {
'Content-Type': 'application/javascript',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
},
html: {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
},
css: {
'Content-Type': 'text/css',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*'
},
答案 0 :(得分:1)
您将fs.readFileSync
用于CSS和JavaScript,而不是fs.readFile
。 Sync
版本从不调用回调,因为它是同步的(它返回数据)。只需在这两个案例分支中将fs.readFileSync
更改为fs.readFile
。