Answer the question
In order to leave comments, you need to log in
Styles and js do not work on html page returned from node.js server. What to do?
I started digging node js yesterday . Cool stuff.
In general, I made a server, launched it through the console.
The code is like this:
var fs = require('fs');
var http = require('http');
var server = http.createServer(function(request, response) {
response.writeHead(200, {'Content-type': 'text/html; charset=utf-8'});
var page = fs.createReadStream('../index.html', 'utf-8');
page.pipe(response);
});
server.listen(3000, '127.0.0.1');
console.log('Сервер запущен');
Answer the question
In order to leave comments, you need to log in
There is a similar question on the toaster: How to serve static in Node.js without Express.js? You can also use the higher-level Express
framework instead of the http module . installation of the simplest web server distribution of static files
var express = require('express');
var app = express();
var port = 3000;
// тут надо отметить что роутеры в Express выполняются последовательно
// и каждый из них имеет возможность прекратить дальнейшую обработку запроса последующими роутерами.
// express.static в случае нахождения запрашиваемого файла так и поступит.
// любой запрос к http://вашдомен_или_IP/public будет восприниматься как запрос статики
app.use('/public', express.static(__dirname + '/public'));
// любой запрос будет восприниматься как запрос статики.
app.use(express.static(__dirname + '/public'));
app.use((err, request, response, next) => {
// логирование ошибки, пока просто console.log
console.log(err)
response.status(500).send(‘Something broke!’)
})
app.listen(port, function () {
console.log('Example app listening on port '+port+'!');
});
if the script and style files are next to index.html, then which server should return them?
the server you wrote is able to handle only one URL: 127.0.0.1:3000 and return only one response - the contents of the file '../index.html'
teach it to process the request 127.0.0.1:3000/my_script.js and return the contents of the js file - and the script will be connected and executed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question