Approach 2 Creating an Instance of Axios
In this approach, we donât use the axios directly in the component, rather we make an instance of Axios with basic backend details such as base API string and basic headers. This helps avoid rewriting the base URL and headers repeatedly. Then we export the instance to make it usable in other components.
Syntax:
const instance = axios.create({
baseURL: 'http://localhost:5000',
headers: {
'Content-Type': 'application/json',
},
});
export default instance;
// import axios from the exported instance
const response = await axios.post('/login', { username, password });
How to send Basic Auth with Axios in React & Node ?
Basic Auth is a simple authentication scheme. It involves sending a username and password with each request to the server through HTTP. Axios is a popular HTTP client for making requests in JavaScript.
In this article, we will create a React App to demonstrate sending basic Auth with Axios and discuss the following approaches:
Table of Content
- Basic approach with Inline Header
- Creating an Instance of Axios
Contact Us