Steps to Create React Application
Step 1: Below is the command to create React app in your project…
npx create-react-app myreactapp
Step 2: Enter in the directory created in the first step.
cd myreactapp
Step 3: Install Axios library using the command given below…
npm i axios
Project Structure:
The Updated dependencies in package.json file.
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: This code snippet uses axios to make an HTTP request to the backend server.
Javascript
// Filename - App.js import React from "react" ; import axios from "axios" ; class App extends React.Component { state = { newfiles: null , }; handleFile(e) { // Getting the files from the input let newfiles = e.target.newfiles; this .setState({ newfiles }); } handleUpload(e) { let newfiles = this .state.newfiles; let formData = new FormData(); // Adding files to the formdata formData.append( "image" , newfiles); formData.append( "name" , "Name" ); axios({ // Endpoint to send files url: "http://localhost:8080/files" , method: "POST" , headers: { // Add any auth token here authorization: "your token comes here" , }, // Attaching the form data data: formData, }) // Handle the response from backend here .then((res) => {}) // Catch errors if any . catch ((err) => {}); } render() { return ( <div> <h1>Select your files</h1> <input type= "file" // To select multiple files multiple= "multiple" onChange={(e) => this .handleFile(e)} /> <button onClick={(e) => this .handleUpload(e)} > Send Files </button> </div> ); } } export default App; |
Steps to Run the Application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/
The above example is just a small code description to showcase how to use Axios in your project. We will discuss multiple methods such as GET, POST, and PUT in Axios in the upcoming section.
Axios in React: A Guide for Beginners
In React, backend communication is typically achieved using the HTTP protocol. While many developers are familiar with the XML HTTP request interface and Fetch API for making HTTP requests, there’s another powerful library called Axios that simplifies the process further.
Table of Content
- Prerequisites
- Introduction to Axios
- Steps to Create React Application
- Need of Axios in React
- GET Request with Axios
- POST Request with Axios:
- Delete Request With Axios:
- Response Objects in Axios
- Error Object:
- Features of Axios Library
- Shorthand Methods in Axios
- Conclusion
Contact Us