Я пытаюсь узнать node.js и немного ударил блокпост.
Моя проблема в том, что я не мог загружать внешний файл css и js в html файл.
GET http://localhost:8080/css/style.css 404 (Not Found)
GET http://localhost:8080/js/script.css 404 (Not Found)
(это было, когда все файлы находились в корневом каталоге приложения)
Мне было предложено несколько подражать следующей структуре приложения, добавить маршрут для публичного каталога, чтобы веб-сервер мог обслуживать внешние файлы.
моя структура приложения похожа на
domain.com
app/
webserver.js
public/
chatclient.html
js/
script.js
css/
style.css
Итак, мой webserver.js script находится в корне приложения, и все, что я хочу получить, находится в 'public'.
Я также видел этот пример, который использует path.extname(), чтобы получить расширения файлов, расположенные в пути. (см. последний блок кода).
Итак, я попытался объединить новую структуру сайта и этот пример пути .extname(), чтобы веб-сервер разрешил доступ к любому файлу в моем общедоступном каталоге, поэтому я могу отобразить html файл, который ссылается на внешние js и css файлы.
Мой webserver.js выглядит следующим образом.
var http = require('http')
, url = require('url')
, fs = require('fs')
, path = require('path')
, server;
server = http.createServer(function(req,res){
var myPath = url.parse(req.url).pathname;
switch(myPath){
case '/public':
// get the extensions of the files inside this dir (.html, .js, .css)
var extname = mypath.extname(path);
switch (extname) {
// get the html
case '.html':
fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
if (err) return send404(res);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data, 'utf8');
res.end();
});
break;
// get the script that /public/chatclient.html references
case '.js':
fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
break;
// get the styles that /public/chatclient.html references
case '.css':
fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
if (err) return send404(res);
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8');
res.end();
});
}
break;
default: send404(res);
}
});
Внутри публичного я пытаюсь получить любую из папок/файлов внутри этого каталога через var extname = mypath.extname(путь); Подобно ссылке, которую я предоставил.
Но в настоящий момент "extname" пуст, когда я консолью его лог.
Может ли кто-нибудь сообщить, что мне может понадобиться, чтобы добавить или tweek здесь? Я знаю, что это можно сделать легко в Express, но я хотел бы знать, как достичь того же, просто полагаясь на node.
Я ценю любую помощь в этом.
Спасибо заранее.