NodeJs中的静态HTTP文件服务器:有时外部.js和.css文件加载正常,有时加载不正常;t

Static HTTP File Server in NodeJs: Sometimes external .js and .css files load properly, sometimes they don't?

本文关键字:加载 文件 不正常 css js 静态 HTTP 文件服务器 NodeJs 外部      更新时间:2023-09-26

编辑:我知道使用express或其他什么会更容易,但这都是一个学习练习,如果这一切都很复杂,很抱歉,哈哈!

编辑2:在添加了一些控制台日志进行调试后,问题似乎与以下事实有关:当浏览器向服务器发出一个请求(例如,对于style.css)时,在完成第一个请求的响应之前,它会发出另一个请求(例如,登录失败.js)。来自浏览器的这些多个请求似乎会导致某种问题,每个后续请求都会阻止前一个请求完成。伊克斯,我需要帮助。

编辑3:经过一些调试后,路径名变量似乎不会在每次请求时更改其值。出于某种原因,路径名的值在每个请求上都保持不变,这使得每个请求的响应都是相同的——更奇怪的是,uri的值在每一个请求上都会发生变化(uri是路径名值的来源…),仍然试图找出为什么会发生这种奇怪的行为。

因此,当服务器请求链接到特定.html文件的外部.js和.css文件时,我一直遇到这个问题。回答总是前后矛盾。例如,有时代码会完美运行,有时css会加载,而js不会加载,有时两者都加载,有时二者都不加载。我无法确定这是因为我的代码是同步的,还是其他原因。这是我的代码:

Server.js

//Module requires
var http = require("http"),
fs = require("fs"),
path = require('path'),
url = require('url'),
invoke = require("./invoke");

//Object "MIMETYPES"
//Maps relationships between file extensions and their respective MIME Content-Types    
var MIMETYPES = {
".html": "text/html",
".jpeg": "image/jpeg",
".jpg": "image/jpeg",
".png": "image/png",
".js": "text/javascript",
".css": "text/css"
};
//Object "invokeOptions"
//Options passed to Invoke() function for POST requests 
var invokeOptions = {
postData : "",
uri : ""
}
var PORT = 8888;
//HTTP Server Begin
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
    pathname = path.resolve(__dirname, "..") + uri;
console.log("Recieved " + req.method + " request for : " + uri);
invokeOptions.uri = uri;
//GET requests wrapper
if (req.method == "GET"){
    //Invoke() function handler for GET requests
    if (path.extname(pathname) == ""){
        invoke.invoke(invokeOptions, req, res);
        return;
    }
    //Static file server for GET requests
    fs.exists(pathname, function(exists) {
        if(!exists) {
            console.log("Requested file ''" + pathname + "'' doesn't exist.");
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.write('404 Not Found'n');
            res.end();
            return;
        }
        var contentType = MIMETYPES[path.extname(pathname)];
        res.writeHead(200, {"Content-Type" : contentType});
        console.log("Current URI: " + uri + " has content type: " + contentType);
        fs.createReadStream(pathname).pipe(res);
        return;
    });
}
//POST requests wrapper
if (req.method == "POST"){
    var postData = "";
    req.on("data", function(postPacket) {
        postData += postPacket;
    });
    req.on("end", function() {
        invokeOptions.postData = postData;
        invoke.invoke(invokeOptions, req, res);
        return;
    }); 
}   
}).listen(PORT);
console.log ("Server listening on port: " + PORT);

Invoke.js-这处理对非文件的请求,即对服务器上的函数的请求

var fs = require("fs"),
querystring = require("querystring"),
path = require("path");
function invoke (options, req, res){
process.stdout.write("Invoking function --> ");
if (options.uri == "/"){
    console.log("Index");
    res.writeHead(200, {"Content-Type" : "text/html"});
    fs.createReadStream("../index.html").pipe(res);
    return;
}
if (options.uri == "/login"){
    console.log("Login");
    fs.readFile(path.resolve("../users.json"), "UTF-8", function(err, data){
        if (err) throw err;
        var json = JSON.parse(data);
        var user = querystring.parse(options.postData).username,
            password = querystring.parse(options.postData).password;
        console.log("Submitted Username:  " + user + "'nSubmitted Password:  " + password);
        if (json.users[0].username == user && json.users[0].password == password){
            res.writeHead(200, {"Content-Type" : "text/html"});
            fs.createReadStream("../app.html").pipe(res);
            return; 
        }
        else {
            res.writeHead(300, {"Content-Type" : "text/html"});
            fs.createReadStream("../login-fail.html").pipe(res);
            return; 
        }
    });     
}
else {
    console.log("Error! Bad request.");
    res.writeHead(400, {"Content-Type" : "text/plain"});
    res.end("Error 400: Bad Request. 'nThere is no function corresponding to that request.");
}
}
exports.invoke = invoke;

登录失败.js-这是几乎从未加载的代码

$(document).ready(function() {
var current = 3;
var countdown = $(".countdown");
function down (){
    current--;
    if (current != 0){
         countdown.text(current);             
    }
    else {
    clearInterval(interval);
    window.location.replace("./");
    }
}
var interval = setInterval(down, 1000);
});

基本上,index.html文件是一个接受用户名和密码的表单,它将提交的POST数据与json文件进行比较,如果它与json中的哈希匹配,它会请求app.html,否则它会请求login-fail.html。当调用登录html文件时,它会链接到css和js,当请求时,它们几乎不会运行!

此外,我认为应该注意的是,当请求css时,"内容类型"的console.log是"text/javascript",而它不起作用。任何帮助都将不胜感激!

天哪。

Pathname没有被声明为每个请求的变量,因为我使用了;而不是,

女士们,先生们,我现在要去死了。

您在login-fail.html中使用的相对路径可能没有正确解析,因为URL路径没有更改(/login),所以浏览器正在查找/login/css/style.css/login/js/login-fail.js。尝试修改login-fail.html以使用绝对路径而不是相对路径。