How to make POST API request in Reactjs


We have already learn about how to make API calls in HTML using jQuery and AJAX , if you do miss the article here is the quick link to the posts.

React

React is a JavaScript UI library for building super responsive web application. We can connect React with Nodejs-Express API/ any API (already covered the API creation with Node-Express in the past tutorials, following links will be helpful for revisiting those posts)

Create API with Node-Express

POST API call with Axios

Axios is a NPM package which let you use API in react. To use axios we have to install the package and make API request.

npm i --save axios

A POST request is used to pass data to the server, for example register a new product to the inventory

onPublish(e) {
    e.preventDefault();
    const post = {
      title: this.state.title,
      content: this.state.content  
    };
    console.log(post);
    axios
      .post("http://localhost:3005/post/create", post)
      .then((res) => console.log(res.data))
      .catch((error) => {
        console.log(error);
      });
  }

In the above code we have make call to the API end point post/create which will save the post to the server.

Following React API posts help you to build better React apps

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.