Home >Web Front-end >Front-end Q&A >nodejs request address

nodejs request address

WBOY
WBOYOriginal
2023-05-13 21:29:11492browse

In the process of web development, we often need to send requests to the backend, obtain data or perform some operations. Node.js provides a quick and easy way to send requests and process the returned content. This article will introduce how to use Node.js to send HTTP/HTTPS requests and process the returned request content.

First, we need to install the request package, which is a popular way to send HTTP requests in Node.js. You can install it with the following command:

npm install request

After the installation is complete, you can use the request package to send HTTP/HTTPS requests.

Send a request

Using requestSending a request is very simple. You only need to pass in a URL parameter, for example:

const request = require('request');

request('https://www.baidu.com', function (error, response, body) {
  console.log('error:', error); // 打印错误信息
  console.log('statusCode:', response && response.statusCode); // 打印响应状态码
  console.log('body:', body); // 打印HTML内容
});

The above code sends a GET request to Baidu website and print the response status code and HTML content.

If you need to send a POST request, you need to pass in an entity containing the request parameters:

const request = require('request');

request.post('https://api.example.com/login', {form: {username: 'example', password: 'password'}}, 
  function (error, response, body) {
    console.log('error:', error); // 打印错误信息
    console.log('statusCode:', response && response.statusCode); // 打印响应状态码
    console.log('body:', body); // 打印响应内容
  }
);

The above code sends a POST request to https://api.example.com/ login, with username and password parameters. form is a parameter entity that contains the requested parameters.

Processing the response

When the request is executed, request will return a response object after the callback, which contains the status code and entity content of the response. You can use response.statusCode to access the response status code and response.body to access the entity content.

In addition to printing the content directly, the returned content can also be parsed and processed. Common processing methods include string parsing, JSON parsing, binary parsing, etc.

For example, when the callback returns HTML content, you can use cheerio or node-html-parser to parse:

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

request('https://www.example.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const $ = cheerio.load(body);
    console.log($('title').text());
  }
});

The above code uses cheerio parses the HTML content and prints the title of the web page.

When the callback returns content in JSON format, you can use the JSON.parse method to parse the JSON string. For example:

const request = require('request');

request('https://api.example.com/users/1', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const user = JSON.parse(body);
    console.log(user.name);
    console.log(user.email);
  }
});

The above code parses the returned JSON content and prints the user's name and email.

When the callback returns binary content, you can use the Buffer object for decoding. For example:

const request = require('request');

request('https://www.example.com/logo.png', {encoding: null}, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    const data = 'data:' + response.headers['content-type'] + ';base64,' + Buffer.from(body).toString('base64');
    console.log(data);
  }
});

The above code obtains a PNG image and uses the Buffer object to decode the returned binary data.

Send HTTPS request

If you need to send HTTPS request, you need to use the https package. The https package is a package that comes with Node.js and does not need to be installed. You can send an HTTPS request like the following code:

const https = require('https');

https.get('https://www.example.com', function (response) {
  console.log('statusCode:', response.statusCode);
  console.log('headers:', response.headers);

  response.on('data', function (data) {
    console.log(data.toString());
  });
});

The above code uses the https.get method to send an HTTPS GET request and prints the response status code and response header. Use the response.on method to listen to the stream of returned content and process it.

HTTPS requests require security authentication, so an HTTPS certificate is required. You can add ca, cert, key and other attributes to the parameters to specify the certificate.

For example:

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

const options = {
  ca: [fs.readFileSync('ca.pem')],
  cert: fs.readFileSync('cert.pem'),
  key: fs.readFileSync('key.pem')
};

https.get('https://www.example.com', options, function (response) {
  console.log('statusCode:', response.statusCode);
  console.log('headers:', response.headers);

  response.on('data', function (data) {
    console.log(data.toString());
  });
});

The above code uses its own certificate, where ca is the certificate chain of the root certificate, cert and key is your own certificate and private key.

Summary

This article introduces how to send HTTP/HTTPS requests in Node.js and how to process the returned content. Finally, it should be noted that sending HTTP requests may involve cross-domain issues, and cross-domain request headers need to be set. At the same time, you also need to pay attention to security issues and performance issues to avoid making too many requests or leaking sensitive information.

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