Node.js - внешние JS и CSS файлы (просто используя Node.js не выразить)
Я пытаюсь узнать 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.
Я ценю любую помощь в этом.
Спасибо заранее.
Ответы
Ответ 1
В вашем коде есть несколько проблем.
- Ваш сервер не будет запускаться, поскольку вы не указали порт для прослушивания.
- Как заметил Эрик, ваше состояние случая не будет выполнено, так как "public" не появляется в URL-адресе.
- Вы ссылаетесь на несуществующую переменную "контент" в ваших ответах js и css, должны быть "данные".
- Заголовок css content-type должен быть text/css вместо text/javascript
- Указание "utf8" в теле не нужно.
Я переписал ваш код.
Заметьте, я не использую case/switch. Я предпочитаю гораздо проще, если и еще, вы можете вернуть их, если это предпочтение. Модули url и path не нужны в моей перезаписи, поэтому я удалил их.
var http = require('http'),
fs = require('fs');
http.createServer(function (req, res) {
if(req.url.indexOf('.html') != -1){ //req.url has the pathname, check if it conatins '.html'
fs.readFile(__dirname + '/public/chatclient.html', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
fs.readFile(__dirname + '/public/js/script.js', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(data);
res.end();
});
}
if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.css'
fs.readFile(__dirname + '/public/css/style.css', function (err, data) {
if (err) console.log(err);
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Ответ 2
Возможно, вы захотите изучить серверные фреймворки, такие как express, которые позволяют вам устанавливать "общедоступный" каталог для автоматической маршрутизации статических файлов
var express = require('express'),app = express();
app.use(express.static(path.join(__dirname, 'public')));
Дешёвые накладные расходы такой структуры действительно стоили бы усилий, чтобы эффективно "изобретать колесо"
Ответ 3
public
не отображается в URL-адресе, запрошенном клиентом, поэтому переключатель myPath всегда будет проваливаться.
Ответ 4
Вы можете рассмотреть возможность использования Static промежуточного ПО, предоставляемого в Connect. Взгляд на статический исходный код может дать вам некоторые идеи о том, как это сделать с помощью кода node.js(если вы хотите узнать, как это сделать, не используя существующую библиотеку).
Ответ 5
// get the extensions of the files inside this dir (.html, .js, .css)
var extname = **mypath**.extname(path);
Они меняются на противоположные. Должно быть:
var extension = path.extname(mypath);
Я также не использую имена функций для имен переменных, когда я могу избежать этого.
Ответ 6
Автоматическое обновление файлов при изменении, задержка для обновления 1 сек.
Формат: app.js | index.htm | style.css
// packages
const http = require('http');
const fs = require('fs');
// server properties
const hostname = '127.0.0.1';
const port = 3000;
const timer = 300;
//should trigger atualize function every timer parameter
let htmlfile = '';
let cssfile = '';
let jsfile = '';
uptodate();
// should read file from the disk for html
function uptodate()
{
console.log(1);
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
htmlfile = html;
});
// should read css from the disk for css
fs.readFile('./style.css', function (err, html) {
if (err) {
throw err;
}
cssfile = html;
});
// should read js file from the disk
fs.readFile('./app.js', function (err, html) {
if (err) {
throw err;
}
jsfile = html;
});
setTimeout(function(){ uptodate(); }, 1000);
}
const server = http.createServer((req, res) => {
res.statusCode = 200;
// should send css and js
if(req.url.indexOf('.css') != -1){ //req.url has the pathname, check if it conatins '.js'
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(cssfile);
res.end();
return;
}
if(req.url.indexOf('.js') != -1){ //req.url has the pathname, check if it conatins '.js'
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.write(jsfile);
res.end();
return;
}
// should send html file via request
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(htmlfile);
res.end();
});
// should send css and js
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});