Trước hết: Tôi không sử dụng Express.Node.js - Tài nguyên được hiểu là Tập lệnh nhưng được chuyển với văn bản MIME/plain
Với cách đó, khi tôi tải tệp index.html
của mình một cách đệ quy readFile
mọi tệp được đính kèm như CSS và JS của tôi. Nhưng nó luôn luôn trả về lỗi này trong thanh tra của tôi (Chrome):
Resource hiểu là Script nhưng chuyển với kiểu MIME text/plain
tôi đã hoàn toàn không biết tại sao nó được làm điều này. Đây là mã của tôi:
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;
Làm cách nào để khắc phục sự cố này? Điều này đã dừng dự án của tôi trong bài hát của nó.
Lưu ý: đây là một sự tiến triển của một vấn đề trước đó tôi đã nói chuyện về ở đây: Node.js incorrect path problems
Trước hết, đó là 'writeHead', không phải 'writeHeader'. Tiếp theo - yikes, đó là 'if'. Bạn nên sử dụng một đối tượng. 'response.writeHead (200, {'Content-Type': mimeTypes [extension]});'. – Ryan
Bắt tốt trên 'writeHead'. Nhưng đối với các mime, xem câu hỏi trước đây của tôi tại http://stackoverflow.com/questions/18004512/node-js-incorrect-path-problems/18004553?noredirect=1#comment26330812_18004553 Đó là cách tôi đã có nó ban đầu. Nó không tạo ra sự khác biệt. Đây là lần lặp lớn thứ hai của tôi. – JDillon522
Bạn đã thử truy cập URL tập lệnh trực tiếp chưa? Nó có hoạt động không? – Ryan