Po pierwsze: nie używam Expressu.Node.js - zasób interpretowany jako skrypt, ale przesłany z tekstem typu MIME/zwykły
Po usunięciu tego, po załadowaniu pliku index.html
, rekursywnie rekompensuje on każdy dołączony plik, taki jak moje strony CSS i JS. Ale to zawsze zwraca ten błąd w moim inspektora (Chrome):
zasobów interpretowany jako skrypt, ale przeniesione z typem MIME text/plain
mam absolutnie żadnego pojęcia, dlaczego to robi. Oto mój kod:
var http = require('http');
var querystring = require('querystring');
var fs = require('fs');
var url = require('url');
function route(handle, pathname, response, request){
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === "function"){
handle[pathname](response, request);
} else {
var file_path = "";
// parses the url request for a file and pulls the pathname
var url_request = url.parse(request.url).pathname;
var tmp = url_request.lastIndexOf(".");
var extension = url_request.substring((tmp + 1));
file_path = url_request.replace("/", "");
//load needed pages and static files
fs.readFile(file_path, function (error, contents){
if(error){
console.log('DIE!');
console.log(error);
response.writeHeader(500, {"Content-Type": "text/html"});
response.end("<h1>FS READ FILE ERROR: Internal Server Error!</h1>");
}
else{
console.log('SUCCESS!');
// set content type
if (extension === 'html') response.writeHeader(200, {"Content-Type": 'text/html'});
else if (extension === 'htm') response.writeHeader(200, {"Content-Type": 'text/html'});
else if (extension === 'css') response.writeHeader(200, {"Content-Type": 'text/css'});
else if (extension === 'js') response.writeHeader(200, {"Content-Type": 'text/javascript'});
else if (extension === 'png') response.writeHeader(200, {"Content-Type": 'image/png'});
else if (extension === 'jpg') response.writeHeader(200, {"Content-Type": 'image/jpg'});
else if (extension === 'jpeg') response.writeHeader(200, {"Content-Type": 'image/jpeg'});
else { console.log("NO CORRECT EXTENSION")};
console.log(extension);
response.end(contents);
}
response.end();
});
response.end();
}
}
exports.route = route;
Jak mogę to naprawić? To zatrzymało mój projekt w jego ślady.
Uwaga: to jest progresja wcześniejszym problem miałem mowa tutaj: Node.js incorrect path problems
po pierwsze, jest to 'writeHead', nie' writeHeader'. Dalej - yikes, że "jeśli". Powinieneś użyć obiektu. 'response.writeHead (200, {'Content-Type': mimeTypes [rozszerzenie]});'. – Ryan
Dobry połów na 'writeHead'. Ale jeśli chodzi o mima, zobacz moje poprzednie pytanie na http://stackoverflow.com/questions/18004512/node-js-incorrect-path-problems/18004553?noredirect=1#comment26330812_18004553 Tak właśnie miałem to pierwotnie. To nie miało znaczenia. To moja druga ważna iteracja. – JDillon522
Czy próbowałeś już od razu odwiedzić URL skryptu? Czy to działa? – Ryan