Home > Web Front-end > Front-end Q&A > nodejs request encapsulation excuse

nodejs request encapsulation excuse

WBOY
Release: 2023-05-11 13:07:38
Original
746 people have browsed it

With the popularity of front-end and back-end separation, front-end engineers increasingly need to interface with the back-end for communication. During this process, many engineers found that there were many problems in directly using native XMLHttpRequest or fetch to make network requests. Therefore, many front-end teams now use third-party request libraries to make interface requests. Among them, the request request library developed by Node.js is also very popular.

In this article, we will introduce how to use the request request library of Node.js to encapsulate interface requests, making it more convenient and faster for front-end engineers to communicate with interfaces.

Install the Request library

Before using the Request library, you need to install it first. It can be installed using the npm command on the command line:

npm install request --save
Copy after login

Send a GET request

Next, we will use the Request library to send some common requests. First, we need to send a GET request using the request.get() method.

const request = require('request');

request.get('https://api.github.com/', function(error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body);
    }
});
Copy after login

In this code, we access GitHub’s API to obtain its homepage content. First, we send a GET request using the request.get() method, passing the GitHub API address as a parameter. It will send the request to the server and wait for the server's response.

When the server responds, the Request library will pass the response information to the callback function. The parameter error indicates whether there is an error during the request process, response indicates the server's response header information, and body indicates the specific content of the server's response.

In this code, we first use if (!error && response.statusCode == 200) to determine whether an error occurs. If there is no error, the response content is printed out.

Send a POST request

Next we send a POST request.

const request = require('request');

request.post({
    url: 'https://httpbin.org/post',
    form: {
        name: '张三',
        age: 18
    }
}, function(error, response, body) {
    if(!error) {
        console.log(body);
    }
});
Copy after login

In this code, we send a POST request through the request.post() method, passing the request address and request parameters in the form of objects. The form parameter represents the form data of the POST request. Here we pass a name and age fields.

Similarly, when the server responds, the Request library will pass the response information to the callback function. We can also determine whether the request is successful by judging error and response.statusCode, and print out the response content.

Send JSON data

In today's front-end and back-end separation development, a very common request method is to send JSON data. The following is a sample code for sending JSON data:

const request = require('request');

const data = {
    name: '李四',
    age: 20
};

const options = {
    method: 'POST',
    url: 'https://httpbin.org/post',
    json: true,
    body: data
};

request(options, function(error, response, body) {
    if(!error) {
        console.log(body);
    }
});
Copy after login

In this code, we first define a data object to represent the JSON data to be sent. Then, we configured some parameters of the request through the options parameter:

  • method represents the request method, here we set it to POST.
  • url represents the request address, which is also https://httpbin.org/post.
  • json means that the data we want to send is in JSON format.
  • body is the specific data we want to send.

In the request() method, we pass the options parameter in. Like the previous sample code, when the server responds, the Request library will pass the response information to the callback function.

Error handling when sending requests

In the process of making interface requests, it is inevitable to encounter many errors, such as network connection timeout, request address does not exist, etc. The following is a sample code for error handling:

const request = require('request');

const data = {
    name: '李四',
    age: 20
};

const options = {
    method: 'POST',
    url: 'https://httpbin.org/post',
    json: true,
    body: data,
    timeout: 5000 // 设置请求超时时间
};

request(options, function(error, response, body) {
    if(error) {
        console.log('请求发生错误:', error);
    } else {
        if(response.statusCode == 200) {
            console.log('响应内容:', body);
        } else {
            console.log('请求失败,状态码:', response.statusCode);
        }
    }
});
Copy after login

In this code, we first set the options.timeout parameter to indicate the timeout of the request to avoid the page being stuck due to the request being too long without a response. If an error occurs, we use console.log() in the callback function to output the error message. If there is no error, the response status code is determined. If the status code is 200, the response content is printed. Otherwise, print the status code of the request failure.

Encapsulating request interface function

When using the Request library to make interface requests, we can encapsulate common request methods to avoid too much repeated code. The following is a sample code that encapsulates the request interface function:

const request = require('request');

function requestApi(url, method, data) {
    const options = {
        method: method,
        url: url,
        json: true,
        timeout: 5000
    };

    if(method == 'GET') {
        options.method = 'GET';
    } else if(method == 'POST') {
        options.method = 'POST';
        options.body = data;
    } else if(method == 'PUT') {
        options.method = 'PUT';
        options.body = data;
    } else if(method == 'DELETE') {
        options.method = 'DELETE';
        options.body = data;
    }

    return new Promise(function(resolve, reject) {
        request(options, function(error, response, body) {
            if(error) {
                reject(error);
            } else {
                if(response.statusCode == 200) {
                    resolve(body);
                } else {
                    reject(response.statusCode);
                }
            }
        });
    });
}
Copy after login

In this code, we first define a requestApi() function. It contains three parameters:

  • url represents the requested address.
  • method represents the requested method.
  • data represents the requested data.

In the function, we define the options object to store some configuration parameters of the request. According to different request methods, we set the value of options.method and the value of options.body.

Then, we use Promise for asynchronous processing. In the callback function of the request() method, we use resolve() to pass the response content and reject() to pass the error message and status code. Using the then() and catch() methods of the Promise object, we can perform corresponding processing after requesting the data.

Summary

Using the Request library of Node.js to make interface requests is a very convenient and fast way. It can avoid some problems caused by using native XMLHttpRequest or fetch directly, and can also handle some common errors. We can encapsulate common requests into functions according to actual needs and call them in the project to make the code more concise and easy to understand.

The above is the detailed content of nodejs request encapsulation excuse. 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