T
T
thelimee2019-04-23 04:45:30
Node.js
thelimee, 2019-04-23 04:45:30

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!');

After that, in the second task, they switched to writing scripts, but no one explained how to connect the js script to the server . Everything works in the html document, as soon as I switch to localhost, the scripts fall off.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-23
@rockon404

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);
});

In the line: the express.static middleware is connected , which will intercept all requests for static files along the path: , for example , pick them up from the folder and return them to the client. 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 question

Ask a Question

731 491 924 answers to any question