gpt4 book ai didi

javascript - ( NodeJS ) Http 服务器不从文件夹加载 JS/CSS 文件

转载 作者:行者123 更新时间:2023-11-29 23:50:14 27 4
gpt4 key购买 nike

<分区>

美好的一天,

我的 NodeJS http 服务器有一个小问题。服务器不从文件夹加载 CSS/JS 文件,仅从 url 加载,我不知道为什么。如果有人能花点时间给我一些关于哪里出了问题的提示,我将不胜感激。

这是服务器代码:

var http = require("http");
var gs = require("querystring");
var url = require("url");
var fs = require("fs");

var server = http.createServer(function (request, response, err) {

//HTML
if (request.url === "/") {
sendFileContent(response, "HTML/Login.html", "text/html");
console.log("Requested URL : " + request.url + "\n");
}
else if (request.url === "/main") {
sendFileContent(response, "HTML/Main_Home.html", "text/html");
console.log("Requested URL : " + request.url + "\n");
}
// JS / CSS / Other formats
else if (/^\/[a-zA-Z0-9\/]*.js$/.test(request.url.toString(1))) {
sendFileContent(response, request.url.toString().substring(1), "text/javascript");
}
else if (/^\/[a-zA-Z0-9\/]*.css$/.test(request.url.toString()))
{
sendFileContent(response, request.url.toString().substring(1), "text/css");
}
else if (/^\/[a-zA-Z0-9\/]*.json$/.test(request.url.toString()))
{
sendFileContent(response, request.url.toString().substring(1), "application/json");
}
else if (/^\/[a-zA-Z0-9\/]*.ts$/.test(request.url.toString()))
{
sendFileContent(response, request.url.toString().substring(1), "text/javascript");
}
else if (/^\/[a-zA-Z0-9\/]*.png$/.test(request.url.toString()))
{
sendFileContent(response, request.url.toString().substring(1), "image/png");
}
else if (/^\/[a-zA-Z0-9\/]*.jpg$/.test(request.url.toString()))
{
sendFileContent(response, request.url.toString().substring(1), "image/jpeg");
}
else
{
console.log("Requested URL : " + request.url + "\n");
response.end();
}
});

server.listen(1337, function ()
{
require("console-stamp")(console, '[HH:MM:ss]');
console.log("HTTP Server runs on port : 1337");

});

console.log("Server ready....");

下面是发送文件内容函数:

function sendFileContent(response, fileName, contentType){
fs.readFile(fileName, function (err, data) {
if (err) {
response.writeHead(404);
response.end("Not Found!");
}
else {
response.writeHead(200, { "Content-Type": contentType });
response.end(data);
}

});
};

这就是我在 html 中调用文件的方式

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="../materialize/css/materialize.min.css" media="screen,projection" />
<link type="text/css" rel="stylesheet" href="../CSS/App.css" />
<title></title>
<script type="text/javascript" src="../jquery/jquery-3.2.0.min.js"></script>
<script type="text/javascript" src="../materialize/js/materialize.min.js"> </script>
<script type="text/javascript" src="../Javascript/Main_App.js"></script>

感谢您的宝贵时间!

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com