POST Request with Axios
Create a new component AddPost for Post requests. This request will add a post to the post list.
Javascript
// Filename - App.js import React from "react" ; import axios from "axios" ; export default class AddPost extends React.Component { state = { postTitle: "" , }; handleChange = (event) => { this .setState({ postTitle: event.target.value }); }; handleSubmit = (event) => { event.preventDefault(); const post = { postName: this .state.postName, }; axios .post( `https: //jsonplaceholder.typicode.com/posts`, { post } ) .then((res) => { console.log(res); console.log(res.data); }); }; render() { return ( <div> <form onSubmit= "{this.handleSubmit}" > <label> Post Name: <input type= "text" name= "name" onChange= "{this.handleChange}" /> </label> <button type= "submit" >Add</button> </form> </div> ); } } |
In the above code, we have made an HTTP Post request and added a new post to the database. The onChange event triggers the method handleChange() and updates the request when the API request returns the data successfully.
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