Home  >  Article  >  Web Front-end  >  nodejs development page jump

nodejs development page jump

PHPz
PHPzOriginal
2023-05-25 11:31:11788browse

With the development of front-end technology, more and more websites and applications are beginning to adopt the Single Page Application (SPA) architecture, and page jumps and data loading are handled by the front-end framework. However, for some more traditional website applications, page jumps still need to be implemented through the backend. This article will introduce how to use Node.js to implement page jump.

1. A preliminary study on Node.js

Node.js is a JavaScript running environment running on the server side. It is built based on the Google V8 JavaScript engine. The emergence of Node.js breaks the shackles that JavaScript can only run on the browser side. It allows JavaScript to run on the server side, making JavaScript an important programming language in full-stack development.

The main advantages of Node.js are:

  1. Single-threaded, asynchronous I/O model: especially suitable for high-concurrency network applications, which can greatly improve performance;
  2. Modular development: Node.js has a large number of built-in modules, which can be used after being introduced through the require function. You can also write the modules yourself;
  3. Lightweight: Node.js is very suitable for handling lightweight Network applications, such as real-time messaging, message push, etc.

Therefore, Node.js is very suitable for developing the backend of some web applications.

2. Implement page jump

In Node.js, to implement page jump, you need to use an HTTP module, which is called "http". We can use it to create a web server, listen to client requests, and return corresponding content. The following is a simple web server code example based on Node.js:

const http = require('http');

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

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

The above code creates an HTTP server, listens to port 3000, and returns "Hello World!" when accessing http://localhost:3000/. ". Next, we need to implement page jump on the server side.

1. Redirect jump

In the HTTP protocol, the server can send a special response header called "Redirect" to tell the client that it needs to jump to another URL. You can use the redirect method of the Node.js response object to implement redirection. The sample code is as follows:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.statusCode = 302;
    res.setHeader('Location', '/login');
    res.end();
  } else if (req.url === '/login') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<html><body><h1>Login Page</h1></body></html>');
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In the above code, when requesting the root path "/", we set the response status code to 302, indicating that redirection is required. Then set the Location field of the response header to "/login". After receiving the response, the client will automatically jump to the "/login" page. When "/login" is requested, we return a piece of HTML code used to render the "login page". Note that when setting response headers, if you need to convert the data into a string, you can use the JSON.stringify() method.

2. Form submission jump

Form submission is a common page jump method, which can submit the data entered by the user to the server for processing. Form submission can be accomplished using HTTP's POST or GET methods. In Node.js, we can also monitor the client's POST or GET requests and perform corresponding logical processing based on the request content. The sample code is as follows:

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

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/login') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`
      <html>
        <body>
          <h1>Login</h1>
          <form method="post" action="/login">
            <label for="username">Username:</label>
            <input type="text" id="username" name="username" required>
            <br>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
            <br>
            <button type="submit">Login</button>
          </form>
        </body>
      </html>
    `);
  } else if (req.method === 'POST' && req.url === '/login') {
    let body = '';

    req.on('data', chunk => {
      body += chunk;
    });

    req.on('end', () => {
      const {username, password} = querystring.parse(body);
      res.setHeader('Content-Type', 'text/html');
      if (username === 'admin' && password === '123456') {
        res.statusCode = 302;
        res.setHeader('Location', '/home');
        res.end();
      } else {
        res.statusCode = 401;
        res.end(`
          <html>
            <body>
              <h1>Invalid Credentials</h1>
            </body>
          </html>
        `);
      }
    });
  } else if (req.method === 'GET' && req.url === '/home') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(`
      <html>
        <body>
          <h1>Welcome to Home</h1>
        </body>
      </html>
    `);
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

In the above code, when the request path is "/login" and the request method is GET, we return a login form page for the user to enter a username and password to log in. When the user clicks the login button to submit the form, the form is submitted to the server in POST mode. We use Node.js's native module querystring to parse the request body of the POST request and determine whether the user name and password entered by the user are correct. If correct, we return a redirect response and automatically jump the browser to the "/home" page; otherwise, we return a 401 status code, indicating unauthorized access.

3. Summary

This article introduces how to use Node.js to implement page jumps, including redirect jumps and form submission jumps. Node.js has the advantages of lightweight, high concurrency, and modular development. It is very suitable for developing the backend of web applications. It is also one of the technologies that has attracted much attention and love in recent years. By studying the knowledge points in this article, I believe you have mastered the method of page jump based on Node.js. I wish you all a happy study!

The above is the detailed content of nodejs development page jump. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:Can't open vue serverNext article:Can't open vue server