编辑:我知道使用express或其他方式会更容易,但这都是一个学习练习,如果这一切都非常复杂,那么很抱歉,哈哈!
编辑 2: 看来(在添加一些控制台日志进行调试之后),问题似乎与以下事实有关:当浏览器向服务器发出一个请求时(例如,对于 style.css),它会在完成第一个请求的响应之前发出另一个请求(例如,对于 login-fail.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;
Login-fail.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,否则请求登录-失败.html。当调用login-html文件时,它已经链接到它的css和js,当请求时它们几乎不会运行!
另外,我认为应该注意的是,当请求CSS时,“content-type”的console.logs是“text/javascript”,当它不起作用时。任何帮助将不胜感激!
最佳答案
天哪。
路径名没有在每个请求中声明为变量,因为我使用了 ;
而不是 ,
女士们先生们,我现在要去死了。
关于javascript - NodeJs 中的静态 HTTP 文件服务器 : Sometimes external . js 和 .css 文件加载正常,有时加载不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994012/