📅  最后修改于: 2023-12-03 15:18:01.760000             🧑  作者: Mango
As a developer, you may need to use various APIs to fetch data when building applications. NPM provides an easy-to-use module called request
which simplifies the process of making HTTP requests in Javascript.
You can install it using npm:
$ npm install request
After installing the request
module, you can make HTTP requests in a few lines of code. Here's an example of how you can make a GET request:
const request = require('request');
request('https://jsonplaceholder.typicode.com/posts/1', function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body); // Print the JSON response
}
});
The request()
function takes a URL parameter as the first argument and a callback function as the second argument. The callback function takes three parameters: error
, response
, and body
.
If the request is successful, error
will be null, response
will contain the metadata about the response (e.g status code), and body
will contain the response content. You can parse the body
in JSON format to retrieve data from the API.
You can also send data (as parameters or payload) with request
using the options
object:
const request = require('request');
const options = {
method: 'POST',
url: 'https://jsonplaceholder.typicode.com/posts',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
};
request(options, function(error, response, body) {
if (!error && response.statusCode == 201) {
console.log(body); // Print the JSON response
}
});
This example sends a POST request to the jsonplaceholder
API with a JSON payload in the request body.
Using the request
module provides a simple and flexible way to make HTTP requests in Javascript. There are many other options that can be used with request
, such as authentication, cookies, and proxies. You can check out the request
documentation for more information.