how to use axios
- User
how to use axios
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
how to use axios
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Axios is a popular JavaScript library used to make HTTP requests from both the browser and Node.js environments. It provides a simple and intuitive API for performing asynchronous operations, handling responses, and managing errors. Axios supports features like interceptors, automatic JSON data transformation, and request cancellation, making it a versatile choice for interacting with APIs.
First, you need to install Axios. You can do this using npm or yarn.
npm install axios
yarn add axios
If you’re working in a browser environment, you can also include Axios via a <script> tag from a CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
This will make axios available globally.
If you're using a module bundler like Webpack or tools like Create React App, you can import Axios as follows:
import axios from 'axios';
In a Node.js environment:
const axios = require('axios');
Here's how to perform a simple GET request to fetch data from an API:
axios.get('https://api.example.com/data')
.then(response => {
// Handle success
console.log(response.data);
})
.catch(error => {
// Handle error
console.error('Error fetching data:', error);
});
To send data to an API using a POST request:
const payload = {
name: 'John Doe',
email: 'john.doe@example.com'
};
axios.post('https://api.example.com/users', payload)
.then(response => {
console.log('User created:', response.data);
})
.catch(error => {
console.error('Error creating user:', error);
});
Axios automatically transforms JSON data. The response object contains several properties:
data: The response payloadstatus: HTTP status codestatusText: Status messageheaders: Response headersconfig: Axios config used for the requestrequest: The request objectExample:
axios.get('https://api.example.com/data')
.then(response => {
console.log('Status:', response.status);
console.log('Data:', response.data);
})
.catch(error => {
if (error.response) {
// Server responded with a status other than 2xx
console.error('Error data:', error.response.data);
console.error('Error status:', error.response.status);
} else if (error.request) {
// Request was made but no response received
console.error('No response:', error.request);
} else {
// Something happened in setting up the request
console.error('Error message:', error.message);
}
});
For cleaner and more readable asynchronous code, you can use async/await.
async function fetchData() {
try {
const response = await axios.get('https://api.example.com/data');
console.log('Data:', response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
async function createUser(user) {
try {
const response = await axios.post('https://api.example.com/users', user);
console.log('User created:', response.data);
} catch (error) {
console.error('Error creating user:', error);
}
}
const newUser = { name: 'Jane Doe', email: 'jane.doe@example.com' };
createUser(newUser);
Interceptors allow you to run code or modify requests/responses before they are handled by then or catch.
// Add a request interceptor
axios.interceptors.request.use(config => {
// Modify config, e.g., add authorization header
config.headers.Authorization = 'Bearer YOUR_TOKEN';
return config;
}, error => {
// Handle request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(response => {
// Any status code within the range of 2xx will trigger this
return response;
}, error => {
// Any status codes outside the range of 2xx trigger this
if (error.response.status === 401) {
// Handle unauthorized errors, possibly redirect to login
}
return Promise.reject(error);
});
You can set default configurations that apply to every request.
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN';
axios.defaults.headers.post['Content-Type'] = 'application/json';
Alternatively, create an Axios instance with custom defaults:
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000, // 1 second timeout
headers: { 'Authorization': 'Bearer YOUR_TOKEN' }
});
// Use the instance for requests
apiClient.get('/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Axios allows you to cancel requests using AbortController (supported in modern browsers and Node.js).
const controller = new AbortController();
const signal = controller.signal;
axios.get('https://api.example.com/data', { signal })
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled:', error.message);
} else {
// Handle error
console.error(error);
}
});
// Cancel the request after 500ms
setTimeout(() => {
controller.abort();
}, 500);
Here's a simple example using Axios in a React application to fetch and display data.
npx create-react-app axios-example
cd axios-example
npm install axios
npm start
App.jsimport React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
// Define async function inside useEffect
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
setData(response.data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, []); // Empty dependency array means this runs once on mount
if (loading) return <p>Loading...</p>;
if (error) return <p>Error fetching data!</p>;
return (
<div>
<h1>Posts</h1>
<ul>
{data.slice(0, 10).map(post => (
<li key={post.id}>
<strong>{post.title}</strong>
<p>{post.body}</p>
</li>
))}
</ul>
</div>
);
}
export default App;
data, loading, and error states.useEffect with an empty dependency array), it fetches posts from a placeholder API.Axios is a powerful and flexible tool for handling HTTP requests in JavaScript applications. Whether you're building a front-end with React, Vue, or Angular, or working on a Node.js backend, Axios simplifies the process of communicating with APIs. Its support for promises, interceptors, and various configuration options makes it a valuable addition to any developer's toolkit.
If you have any specific questions or need further examples, feel free to ask!