Node.js from getting started to giving up

Keywords: node.js

ejs template engine

The following is the simplest node.js route: handle different business logic according to different url requests

import http from 'http'
import url from 'url'

http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf8'})
    const pathName = url.parse(req.url).pathname
    if (pathName === '/login') {		// Different business logic is processed according to different pathName paths
       	res.end('Login page')
    } else if (pathName === '/register') {
        res.end('Registration page')
    } else {
        res.end('404 page')
    }
}).listen(3000)

1. Install ejs template engine

npm install ejs --save

2. Use ejs template engine

Create a views directory to store EJS templates. Create a new login.ejs file in the views directory. As shown below, we find that the EJS file is very similar to the html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Login page</h1>
</body>
</html>

Render the login.ejs template file you just created using the ejs.renderfile method

import http from 'http'
import url from 'url'
import ejs from 'ejs'
http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf8'})
    const pathName = url.parse(req.url).pathname
    if (pathName === '/login') {
       ejs.renderFile('./views/login.ejs', {}, (error, data) => {
           res.end(data)
       })
    } else if (pathName === '/register') {
        res.end('Registration page')
    } else {
        res.end('404 page')
    }
}).listen(3000)

The effect of browser rendering is as follows:

3. Transfer value to ejs template engine

// Pretend to get data from the database
const data = 'hello world!'
const list = [{id: 1, name: 'Zhuge Liang'}, {id: 2, name: 'Sun WuKong'}]
// The second parameter of the renderFile method passes data
ejs.renderFile('./views/login.ejs', {title: data, list}, (error, data) => {
    res.end(data)
})

Modify the login.ejs file to receive the passed data

1. Receive variable <% = prop% >, prop represents variable
2. Loop, js code written in <% js code% >
3. Please refer to EJS template engine for specific usage ejs Chinese document

<h1>Login page</h1>
<h2><%=title%></h2>
<ul>
	<% for(let i = 0; i < list.length; i++) {%>
		<li><%=list[i].name%></li>
	<%}%>
</ul>

The effect of browser rendering is as follows:

get/post get data

Login template page login.ejs

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Login page</h1>
    <form action="handleLogin" method="get">
        <label for="userName">user name:</label><input type="text" name="userName" id="userName"/> 
        <label for="password">password:</label><input type="password" name="password" id="password"/>
        <button type="submit">Sign in</button>
    </form>
</body>
</html>

Homepage template page index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Hello, I'm home!</h1>
</body>
</html>

server.js

import http from 'http'
import url from 'url'
import ejs from 'ejs'
import fs from 'fs'
http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/html;charset=utf8'})
    const pathName = url.parse(req.url).pathname
    // Render ejs login page according to route
    if (pathName === '/login') {
        ejs.renderFile('./views/login.ejs', (error, data) => {
            res.end(data)
        })
    } else if (pathName === '/handleLogin') {
        let str = ''
        // Get request to get query parameters
        if (req.method === 'GET') {
            const query = url.parse(req.url, true).query
            // Jump to home page
            ejs.renderFile('./views/index.ejs', { data: query }, (error, data) => {
                res.end(data)
            })
        }
        // post request get parameters
        if (req.method === 'POST') {
            req.on('data', chunk => {
                str+=chunk
            })
            req.on('end', () => {
            	// Write a file to simulate storing user information in the database
                fs.appendFile('user.txt', `${str}\n`, () => {})
                res.end('Login succeeded!')
            })
        }
    } else {
        res.end('404 page')
    }
}).listen(3000)

The login page form method property is set to get or post

The get request parameters are on the url, and the parameters are obtained and rendered on the ejs template

The post request parameters are on the FormData. Obtain the parameters and write them to the user.txt file to simulate and store them in the database

Digression:
In a simple login scenario, we generally store the user information registered by the user in the database. When the user logs in, first query whether the user exists from the database. If it does not exist, remind the user to register. If yes, the account and password entered by the user are matched, which is inconsistent with the user information stored in the database, indicating that the account or password entered by the user is wrong.
However, in the actual development, the login scenarios are often complex and diverse, such as code scanning login, single sign on, mobile phone verification code login, mobile phone number one click login, etc. for security, the login account and password often need to be encrypted, and sometimes the user needs to manually slide image verification to prevent automatic program attacks, etc, The issues to be considered need to be comprehensive and in-depth. The magnificent Great Wall is built block by block, and a complete project is also composed of code sections, so we need to learn the basic knowledge step by step. Learning is endless, please don't give up, come on!

Posted by maxat on Mon, 20 Sep 2021 19:27:51 -0700