Open In App

How to make POST call to an API using Axios.js in JavaScript ?

Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain Javascript or with any library accordingly. 

The following script-src will include axios.js in the head section of your HTML code 



<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

When we send a request to the API using axios, it returns a response. The response object consists of: 

For the purpose of demonstration, we will be hosting an API on the localhost: 



http://127.0.0.1:5000

Python Script: You will be requiring the following packages to run the API: flask, requests, jsonify, and flask_cors. The code for the Python API is as follows:

Example: 




from flask import Flask, jsonify, request
from flask_cors import CORS
 
app = Flask(__name__)
CORS(app)
 
@app.route('/test', methods =['POST'])
def test():
   return jsonify({"Result": "Welcome to GeeksForGeeks, "
                                   +request.json['name']})
 
if __name__ == '__main__':
    app.run(debug = True)

Note: You can host this API by simply running the above python code.
JS Script: Include axios.js and the corresponding JS file in the HTML file. In the JS file, write the following code which makes a POST request using axios to the API. A POST request to the API requires the following variables:  

Example: 




function makePostRequest(path, queryObj) {
    axios.post(path, queryObj).then(
        (response) => {
            let result = response.data;
            console.log(result);
        },
        (error) => {
            console.log(error);
        }
    );
}
 
queryObj = { name: 'Chitrank' };
makePostRequest('http://127.0.0.1:5000/test', queryObj);

Output: It will call the API with a POST request carrying the mentioned header data. The response obtained will be obtained on the console window.  


Article Tags :