When you need to make HTTPS requests in a JavaScript application, axios is a popular HTTP client library that can be easily used in both browser and Node.js environments. Here are the steps and examples for making HTTPS requests with axios.
Introducing Axios
In your project, you first need to install and import axios. If you are using Node.js, you can install it with the following command:
bashnpm install axios
Then, import it in your code:
javascriptconst axios = require('axios');
If you are using axios in the browser, you can directly include it via a <script> tag:
html<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Making HTTPS Requests
With axios, you can easily make GET, POST, PUT, DELETE, and other HTTP requests. Here is a simple example of making an HTTPS GET request:
javascriptaxios.get('https://api.example.com/data') .then(response => { // Handle successful response console.log(response.data); }) .catch(error => { // Handle request failure console.error('Error fetching data: ', error); });
Here is an example of making an HTTPS POST request, including sending data in the request body:
javascriptconst postData = { userId: 1, title: 'Sample Post', body: 'This is a sample post.' }; axios.post('https://api.example.com/posts', postData) .then(response => { // Handle successful response console.log('Post created: ', response.data); }) .catch(error => { // Handle request failure console.error('Error creating post: ', error); });
Handling Request Parameters
You can include query parameters in GET requests by passing a parameters object to the params property:
javascriptaxios.get('https://api.example.com/data', { params: { userId: 123 } }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error fetching data: ', error); });
Setting Request Headers
Sometimes you may need to set specific HTTP headers, such as when sending authentication information or setting content types. Here is an example of setting HTTP headers in an axios request:
javascriptaxios.get('https://api.example.com/data', { headers: { 'Authorization': 'Bearer YOUR_TOKEN', 'Content-Type': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.error('Error with response: ', error.response); });
Using Axios Instances
You can also create an axios instance to configure common settings for a series of requests, such as the base URL, headers, and timeouts.
javascriptconst apiClient = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); apiClient.get('/data') .then(response => { console.log(response.data); }) .catch(error => { console.error('Error with response: ', error.response); });
Through these steps and examples, you can see that axios provides a concise and powerful way to make HTTPS requests, and it supports various request and configuration options.