Answer the question
In order to leave comments, you need to log in
How to connect js file to Node.js server?
Good afternoon,
I recently dug out a course in which I began to study NodeJS, and FrontEnd in general. The course is merged, so no one answers the questions. So, in the first lesson, a simple server was written:
const http = require('http');
const fs = require('fs');
const server = http.createServer(function (request, responce) {
if (request.url == '/public/style.css'){
const css = fs.readFileSync('public/style.css', 'utf8');
responce.end(css)
}else {
const html = fs.readFileSync('public/index.html', 'utf8')
responce.end(html); //Обработка запроса
}
})
server.listen(process.env.PORT || 3000);
console.log('Server started!');
Answer the question
In order to leave comments, you need to log in
Install express:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.use('public', express.static('public'));
app.get('*', (req, res) => {
res.sendFile('public/index.html');
});
app.listen(port, () => {
console.log('Server listen at %s port', port);
});
app.use('public', express.static('public'));
hostname:port/public/*
http://localhost:3000/public/style.css
/public
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question