I
I
Isherath2018-10-03 14:11:08
Node.js
Isherath, 2018-10-03 14:11:08

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('Сервер запущен');

When opened in a browser, bare html is displayed , and styles and js in rel and script tags , respectively, do not work. js
only works when I write code inside script tags , but not when just a link to the code is specified in the src attribute of this tag. How to be, what to read, what to do, tell me, please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2018-10-03
@Isherath

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

an example of an Express application distributing statics
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+'!');
});

S
Sergey V, 2018-10-03
@dthpth

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 question

Ask a Question

731 491 924 answers to any question