got package #
got is a popular and lightweight HTTP client for Node.js that simplifies the process of making HTTP requests. It features a clean and concise API, built-in support for promises, and various options for customization. Here’s a basic overview of using got in Node.js:
Installation: #
Install got using npm:
npm install got
Making GET Requests: #
Use got to make a simple GET request:
const got = require('got');
got('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Passing Parameters: #
Include parameters in the request for query strings:
got('https://jsonplaceholder.typicode.com/posts', {
searchParams: {
userId: 1,
_limit: 5,
},
})
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Making POST Requests: #
Send data in a POST request:
got.post('https://jsonplaceholder.typicode.com/posts', {
json: {
title: 'foo',
body: 'bar',
userId: 1,
},
})
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Handling Response: #
Access response data and status:
got('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Status:', response.statusCode);
console.log('Response Data:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Handling Errors: #
got automatically rejects promises on HTTP error responses (e.g., status codes 4xx and 5xx):
got('https://jsonplaceholder.typicode.com/nonexistent')
.then(response => {
console.log('Response Data:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
console.error('Status:', error.response.statusCode);
});
Setting Headers: #
Customize headers for the request:
got.post('https://jsonplaceholder.typicode.com/posts', {
json: {
title: 'foo',
body: 'bar',
userId: 1,
},
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
})
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Configuring got Instances: #
Create and configure got instances for consistent settings across requests:
const instance = got.extend({
prefixUrl: 'https://jsonplaceholder.typicode.com',
responseType: 'json',
headers: {
'Content-Type': 'application/json',
},
});
instance.get('/posts/1')
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Retrying Requests: #
Enable automatic retries for failed requests:
got('https://jsonplaceholder.typicode.com/posts/1', {
retry: 3,
throwHttpErrors: false, // to catch errors in the promise chain
})
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
console.error('Error:', error.message);
});
Cancellation: #
got supports cancellation of requests:
const { CancelToken } = got;
const source = CancelToken.source();
got('https://jsonplaceholder.typicode.com/posts/1', {
cancelToken: source.token,
})
.then(response => {
console.log('Response:', response.body);
})
.catch(error => {
if (got.CancelError.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
console.error('Error:', error.message);
}
});
// Cancel the request
source.cancel('Request canceled by the user');
got simplifies the process of making HTTP requests in Node.js, providing a concise and versatile API for handling various HTTP methods, parameters, and response data. Its focus on simplicity, promise-based approach, and features like automatic retries and request cancellation make it a preferred choice for many developers working on both server-side and client-side applications.