Home  >  Article  >  Web Front-end  >  nodejs request request

nodejs request request

PHPz
PHPzOriginal
2023-05-08 09:58:381188browse

Node.js is a JavaScript runtime environment based on the Chrome V8 engine that makes it easy to build high-performance, scalable web applications. Among them, the request module is a very commonly used network request module in Node.js. It allows us to send HTTP/HTTPS requests in Node.js. This article will introduce how to use the request module and how to process the data returned by the request.

1. Install the request module

Before using the request module, you need to install the request module first. Just enter the following command in the console:

$ npm install request --save

This will install the request module into your project and add it to the package.json file.

2. Send a GET request

Sending a GET request is very easy, just use the request method of the request module. The following is a simple example:

const request = require('request');

request('https://api.github.com/users/octocat', (error, response, body) => {
  console.log('statusCode:', response && response.statusCode);
  console.log('body:', body);
});

This example will send a GET request to GitHub's user API to query the user information with the username octocat. The way to send a request is very simple, just call the request method and pass in the requested URL.

The parameters of the callback function are error, response and body. Among them, error represents a request error; response represents a response object, which contains information such as response headers and response codes; body represents the response body, which is the data returned by the API.

3. Send a POST request

Sending a POST request is also very easy. You only need to set the second parameter (ie options) of the request method to the specific request information. The following is an example of using the POST method to add a repo named test to the GitHub API:

const request = require('request');

const options = {
  url: 'https://api.github.com/user/repos',
  headers: {
    'User-Agent': 'request'
  },
  json: true,
  body: {
    name: 'test'
  },
  auth: {
    'user': 'username',
    'pass': 'password'
  }
};

request.post(options, (error, response, body) => {
  console.log('statusCode:', response && response.statusCode);
  console.log('body:', body);
});

In this example, we set the url to https://api.github.com/user/repos, That is GitHub's API for creating warehouses. The headers include User-Agent, indicating that the request was sent by request. Body is the data we want to send, which is the name of the repo we want to create on GitHub. If json is set to true, it means that the data sent is in JSON format. auth means that authentication is required, including username and password.

4. Processing response data

After sending the request, we need to process the response data. For data in JSON format, it can be parsed directly into JavaScript objects. The following is an example of parsing the JSON data returned by the GitHub API into a JavaScript object:

const request = require('request');

request('https://api.github.com/users/octocat', {json: true}, (error, response, body) => {
  console.log('statusCode:', response && response.statusCode);
  console.log('login:', body.login);
  console.log('name:', body.name);
});

In this example, we set json in options to true, which means that when receiving the response data, it is automatically parsed into JSON concatenation. Convert to JavaScript object. In the callback function, we can directly access the login and name properties in the response body.

For data in other formats, we can use the corresponding parsing library to parse. For example, for data in HTML format, you can use the cheerio library for parsing. The following is an example of using cheerio to parse Baidu search results:

const request = require('request');
const cheerio = require('cheerio');

request('https://www.baidu.com/s?wd=nodejs', (error, response, body) => {
  const $ = cheerio.load(body);
  $('h3.t a').each((i, el) => {
    console.log($(el).text());
    console.log($(el).attr('href'));
  });
});

In this example, we request the results of Baidu search keyword nodejs through request. Use cheerio's load method to convert HTML data into a manipulable DOM object. Next, we select the h3.t a element through the selector and loop through each element. Inside the loop, we wrap the element with $() to easily get the element's text and href attribute values.

5. Summary

The above is the basic method of sending HTTP/HTTPS requests using the request module of Node.js. Through this module, we can easily send GET, POST, etc. requests and process the data returned by the request. Although this module is very convenient, you need to pay special attention to security when using it, especially when sending a POST request, the request parameters need to be encrypted.

The above is the detailed content of nodejs request request. 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:vue data hide displayNext article:vue data hide display