What about Node.js GET and POST requests?

Node.js is a JavaScript runtime based on the Chrome V8 engine that enables JavaScript to run on the server side. As a powerful back-end development tool, Node.js provides rich modules and functions, enabling developers to easily build high-performance network applications.

This article will focus on GET and POST requests in Node.js. GET and POST are two commonly used request methods in the HTTP protocol, and they have different characteristics in transmitting data and accessing resources. Knowing how to handle both request styles in Node.js is critical to building web applications.

GET request

What is a GET request

A GET request is a way to request a resource from a server. It appends the request parameters to the request via the URL and sends the request to the server. GET requests are usually used to obtain data, such as reading articles, obtaining user information, and other operations.

Handling GET requests in Node.js

Handling GET requests requires the use of Node.js built-in modules httpor third-party modules express. The two methods will be introduced below.

Use the http module to handle GET requests

const http = require('http');

const server = http.createServer((req, res) => {
    
    
  // 处理 GET 请求逻辑
  if (req.method === 'GET' && req.url === '/data') {
    
    
    // 获取请求参数
    const query = new URL(req.url, `http://${
      
      req.headers.host}`).searchParams;
    const id = query.get('id');

    // 根据参数获取数据
    const data = getDataById(id);

    // 返回数据
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(data));
  } else {
    
    
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, we create an HTTP server and handle the GET request logic in the request event. First, we judge whether the request method and request URL meet expectations. If the requirements are met, we can URLobtain the request parameters through the object and perform corresponding operations, such as obtaining data according to the parameters. Finally, we return the data to the client as JSON format.

Use the express framework to handle GET requests

If you prefer to use a more concise and efficient framework, you can choose to use expressthe module to handle GET requests. Below is a expresssample code that handles GET requests using .

const express = require('express');
const app = express();

app.get('/data', (req, res) => {
    
    
  // 获取请求参数
  const id = req.query.id;

  // 根据参数获取数据
  const data = getDataById(id);

  // 返回数据
  res.json(data);
});

app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, we expresscreated an application using the method and gethandle the GET request using the method. Objects can be used req.queryto directly obtain request parameters and perform corresponding operations. Finally, we use res.json()the method to return the data to the client in JSON format.

POST request

What is a POST request

A POST request is a way of submitting data to a server. It puts the data that needs to be submitted in the request body and sends the request to the server. POST requests are typically used for operations such as creating, updating, or deleting resources.

Handling POST requests in Node.js

Handling POST requests also requires the use of Node.js built-in modules httpor third-party modules express. The two methods are described below.

Use the http module to handle POST requests

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

const server = http.createServer((req, res) => {
    
    
  // 处理 POST 请求逻辑
  if (req.method === 'POST' && req.url === '/data') {
    
    
    let body = '';

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

    req.on('end', () => {
    
    
      // 解析请求体
      const data = JSON.parse(body);

      // 执行相应操作
      saveData(data);

      // 返回响应
      res.statusCode = 200;
      res.end('Data saved successfully');
    });
  } else {
    
    
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, we create an HTTP server and handle the POST request logic in the request event. First, we get the request body data by listening to datathe event and event. endThen, we can parse the request body data and perform corresponding operations, such as saving the data to a database or a file. Finally, we return the successful saving information to the client.

Use the express framework to handle POST requests

expressHandling POST requests using is also very neat. Below is a expresssample code that handles a POST request using .

const express = require('express');
const app = express();

app.use(express.urlencoded({
    
     extended: true }));
app.use(express.json());

app.post('/data', (req, res) => {
    
    
  // 获取请求体数据
  const data = req.body;

  // 执行相应操作
  saveData(data);

  // 返回响应
  res.send('Data saved successfully');
});

app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, we created expressan application using the method and posthandle the POST request using the method. The request body data can be obtained directly through req.bodythe object, and corresponding operations can be performed. Finally, we use res.send()the method to return the successfully saved information to the client.

Summarize

This article details how to handle GET and POST requests in Node.js. GET requests are suitable for obtaining resources and reading data, while POST requests are suitable for operations such as submitting data and creating, updating or deleting resources. You can choose the appropriate way to handle these two requests according to your specific needs.

When handling GET and POST requests, you can use Node.js built-in httpmodules or third-party modules express. httpThe module provides a low-level API, which can flexibly handle request logic; while expressprovides a more advanced and concise API, which can quickly build Web applications.

Through the study of this article, I believe you have mastered the method of handling GET and POST requests in Node.js.

Guess you like

Origin blog.csdn.net/weixin_43025343/article/details/131919456