Home > Web Front-end > Front-end Q&A > Nodejs builds web website

Nodejs builds web website

WBOY
Release: 2023-05-11 22:18:35
Original
1874 people have browsed it

With the continuous development of Web technology, Node.js has become one of the most widely used development languages. Node.js is a JavaScript runtime environment based on the Chrome V8 engine, suitable for building fast, scalable web applications. In this article, we will introduce the process of building a web website using Node.js.

1. Environment setup

Before starting, you need to set up the environment first. It is recommended to use the LTS version of Node.js, download the installation package for the corresponding system from the official website (https://nodejs.org/en/), and install it.

After the installation is complete, you need to confirm whether the environment variables of Node.js are configured successfully. Open the command line window and enter node -v. If the version number appears, the installation is successful.

2. Build an HTTP server

Node.js provides the http module, through which you can create a Web server. Among them, the createServer() method creates an HTTP server, and the listen() method listens to the specified port and IP address.

The code is as follows:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World!
');
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

The above code creates a simple HTTP server that listens to the local port 3000. Enter http://127.0.0.1:3000/ in the browser to access the page on the server. The page content is Hello World!.

3. Processing routing

If you just simply send Hello World to the client! message, then using an HTTP server is sufficient. However, in actual development, you will encounter more complex request response scenarios and need to handle routing.

In this example, assume there are two pages: /home and /about. When requesting access to these two pages, different handling is required. Therefore, routing processing can be added in the HTTP server.

The code is as follows:

const http = require('http');
const url = require('url');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;
    if (uri === '/home') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Welcome to the homepage!
');
    } else if (uri === '/about') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('About the website!
');
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found
');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

In the above code, the built-in url module of Node.js is used to parse the requested url address into pathname for routing processing. When the requested pathname is /home, the server returns "Welcome to the homepage!"; when the requested pathname is /about, the server returns "About the website!"; when the requested pathname does not exist, the server returns 404 Not Found .

4. Use template engine

In the actual development process, using the template engine can greatly improve development efficiency. Commonly used template engines include ejs, handlebars, jade, etc. In this example, the ejs template engine is used for page rendering.

First, install the ejs module through npm:

npm install ejs --save
Copy after login

Make modifications in the HTTP server and use the template engine to render the HTML page:

const http = require('http');
const url = require('url');
const ejs = require('ejs');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;

    if (uri === '/home') {
        fs.readFile('./views/home.ejs', 'utf8', (err, data) => {
            if (err) {
                console.log(err);
                res.statusCode = 404;
                res.setHeader('Content-Type', 'text/plain');
                res.end('File not found!
');
            } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                const template = ejs.compile(data);
                const html = template({title: 'Home Page', message: 'Welcome to the homepage!'});
                res.end(html);
            }
        });
    } else if (uri === '/about') {
        fs.readFile('./views/about.ejs', 'utf8', (err, data) => {
            if (err) {
                console.log(err);
                res.statusCode = 404;
                res.setHeader('Content-Type', 'text/plain');
                res.end('File not found!
');
            } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                const template = ejs.compile(data);
                const html = template({title: 'About Page', message: 'About the website!'});
                res.end(html);
            }
        });
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found
');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

In the above code, the fs module is used Read the template file, use the ejs module to render the template file, and return the generated HTML page to the client.

5. Use static files

In actual development, static files are usually used, such as images, CSS files, JavaScript files, etc. Node.js provides a static file service that can be used to handle requests for static files.

The code is as follows:

const http = require('http');
const url = require('url');
const ejs = require('ejs');
const fs = require('fs');
const path = require('path');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const uri = url.parse(req.url).pathname;
    const filename = path.join(process.cwd(), uri);

    fs.exists(filename, (exists) => {
        if (!exists) {
            res.statusCode = 404;
            res.setHeader('Content-Type', 'text/plain');
            res.end('404 Not Found
');
            return;
        }

        if (fs.statSync(filename).isDirectory()) {
            filename += '/index.html';
        }

        fs.readFile(filename, 'binary', (err, file) => {
            if (err) {
                res.statusCode = 500;
                res.setHeader('Content-Type', 'text/plain');
                res.end(err + '
');
                return;
            }

            res.statusCode = 200;
            const extname = path.extname(filename);
            res.setHeader('Content-Type', mimeTypes[extname] || 'text/plain');
            res.write(file, 'binary');
            res.end();
        });
    });
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});
Copy after login

In the above code, the fs module is used to determine whether the requested file exists, the path module is used to process the path, and mimeTypes is used to define the file type. If the requested file does not exist, 404 Not Found is returned; if the request is a folder, the index.html file in the folder is requested by default; if the file is read successfully, 200 is returned, and the Content-Type header and response are set at the same time. body.

Through the above operations, we successfully built a Web website using Node.js and implemented basic routing processing and static file services. Through further study and practice, we can make more complex Web sites and implement more functions, such as database operations, request agents, etc.

The above is the detailed content of Nodejs builds web website. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template