Home > Web Front-end > Front-end Q&A > Nodejs builds a server on the server

Nodejs builds a server on the server

WBOY
Release: 2023-05-18 15:08:38
Original
1644 people have browsed it

In recent years, Node.js, as an efficient and fast JavaScript running environment, has been widely used in server-side development. The characteristic of Node.js is that it uses event-driven, non-blocking I/O and other technologies to implement lightweight and efficient server-side applications. Let's explore the specific steps to build a server with Node.js.

1. Install Node.js

To build a server locally, you need to install Node.js locally first. The Node.js official website provides installation packages for different operating systems such as Windows, Mac, and Linux. Users can download them according to their own system versions. After the installation is complete, enter node -v in the terminal to check whether Node.js has been successfully installed.

2. Create a server

In Node.js, you can quickly build an HTTP server through the HTTP module. The following is a simple example of setting up an HTTP server:

const http = require('http');
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, () => {
  console.log(`Server running at http://localhost:${port}/`);
});
Copy after login

This code uses the http module of Node.js, uses the createServer method to create an HTTP server, and listens to port 3000. When processing the request, the server returned a status code 200 and a "Hello World" string.

3. Access the server

When the server is running, we can enter http://localhost:3000 in the browser to access the server. Here, the port we set is 3000, so enter http://localhost:3000 in the browser to access our server, and the page will display a "Hello World" string.

4. Processing requests

In the real server setup, we need to further process the requests sent through the client. The http module of Node.js provides two objects, request and response, to help us process requests. The following is a more practical example:

const http = require('http');
const port = 3000;

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

  if (req.url === '/api/time') { // 如果请求的是api/time接口
    res.end(new Date().toString())  // 返回服务器的当前时间
  } else {
    res.end('Hello World!'); // 返回"Hello World"
  }
});

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

In this example, when the request is /api/time, the server returns the current time of the server; when requesting other paths, the server returns "Hello World" String.

5. Middleware

Middleware is a function that is executed during the complete request and response life cycle. They can be used to perform some common operations necessary for all requests, such as authentication, logging, parsing request parameters, etc. In Node.js web applications, the middleware pattern can maximize code reuse and make the project structure clearer. The following is an example of using middleware:

const http = require('http');
const port = 3000;

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

const logger = (req, res, next) => { // 中间件函数
  console.log(`${req.method} ${req.url}`); // 记录请求信息
  next(); // 执行下一个中间件
};

server.use(logger); // 注册中间件

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

In this example, we use the middleware mode and use the middleware function logger to record HTTP requests.

6. Summary

Through the above steps, we can easily use Node.js to build a server and deploy web applications. The high efficiency of Node.js and the ease of learning of JavaScript make Node.js more and more widely used in server-side applications. Next, we can learn more about Node.js, learn WebSocket, Express and other frameworks, and apply them in projects.

The above is the detailed content of Nodejs builds a server on the server. 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