Привет всем,

Добро пожаловать еще раз.

Это третий учебник из этой серии. Если вы не сталкивались с предыдущими уроками, предлагаю пройти здесь.

В этой истории мы увидим, как выполнять маршрутизацию между различными HTML-страницами.

Давайте создадим две страницы HTML. (index.html, логин.html)

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Test Doc</title>
  </head>
  <body>
    <h1>It works!</h1>
  </body>
</html>

логин.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Login</title>
  </head>
  <body>
    <h1>The Login Page</h1>
  </body>
</html>

сервер.js

//initializing the http server
var http = require('http');
//initializing the app.js file where we are going to do routing
var app = require('./app');
//call the handleRequest function and server creation 
http.createServer(app.handleRequest).listen(8000);

Здесь мы собираемся создать еще один файл app.js для выполнения операций маршрутизации.

app.js

//declarations
var url = require('url');
var fs = require('fs');
//renderHTML function 
function renderHTML(path, response) {
  //reading data from variable path
  //path will be defined inside module.exports 
  fs.readFile(path, null, function(error, data) {
    if (error) {
      response.writeHead(404);
      response.write('File not found!');
    } else {
      //write the HTML page
      response.write(data);
    }
    response.end();
  });
}
//to exports the content of the page to server
module.exports = {
  //handleRequest function to access HTML as previous 
  handleRequest: function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    
    //getting url while switched to another page
    //url.parse to get the exact path name
    var path = url.parse(request.url).pathname;
    switch (path) {
      case '/':
        renderHTML('./index.html', response);
        break;
      case '/login':
        renderHTML('./login.html', response);
        break;
      default:
        response.writeHead(404);
        response.write('Route not defined');
        response.end();
    }
  }
};

Просмотрите комментарии, чтобы понять код.

Теперь, как обычно, запускаем $node server.js и видим localhost:8000.

По умолчанию он открывает index.html. Если вы введете login.html вместо index.html, вы увидите содержимое из login.html.

Вот и все. В следующей истории давайте создадим наше первое экспресс-приложение.

Если у вас есть какие-либо сомнения, не стесняйтесь спрашивать в разделе комментариев ниже.

Быть в курсе!