Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

axios get data

import axios from 'axios';
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
Comment

axios post

const axios = require('axios');
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Comment

axios get example

Axios is a simple promise based HTTP client for the browser and node.js. Axios
provides a simple to use library in a small package with a very extensible.

Just like javascript fetching functionalities, axios provides the the fetching
data functionality from api.

Install axios using npm:
 $ npm install axios
 
Install axios Using bower:
 $ bower install axios

Install axios using yarn:
  $ yarn add axios

Import axios as follows:
  const axios = require('axios').default;

// Make a get request with axios sample code 
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });  
  
You can start learning on axios from the below website:
https://axios-http.com/docs/intro
Comment

how to use axios get

const req = async () => {
  const response = await axios.get('https://dog.ceo/api/breeds/list/all')
  console.log(response)
}
req() // Calling this will make a get request and log the response.
Comment

axios get request

import axios from "axios";
/// GET REQUEST
/// Example 1 : Start
// Simple Get Request using Axios
function getData() {
  return axios.get("url");
}
/// Example 1 : End
///
/// Example 2 : Start
// Get Request with Params
getData({ page: page, limit: 5, sort: "name", order: "ASC" })
      .then((res) => {
        // console.log(res);
        // op -> {data: Array(5), status: 200, statusText: "OK", headers: Object, config: Object…}
        // console.log(res.data);
        // op ->  [Object, Object, Object, Object, Object]
        setData(res.data);
      })
      .catch((err) => console.log(err));

function getData(params = {}) {
  // console.log(params); // op -> {page: 1, limit: 5, sort: "name", order: "ASC"}
  return axios.get("url", {
    params: {
      _page: params.page,
      _limit: params.limit,
      _sort: params.sort,
      _order: params.order
    }
  });
}
/// Example 2 : End

Comment

axios get

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
Comment

axios get request

const axios = require('axios');

async function makeGetRequest() {

  let res = await axios.get('http://webcode.me');

  let data = res.data;
  console.log(data);
}

makeGetRequest();
Comment

axios get Method

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
Comment

axios api post request

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);
Comment

axios post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  
 https://axios-http.com/docs/post_example
Comment

axios post

axios.post('https:sample-endpoint.com/user', {
    Name: 'Fred',
    Age: '23'
  })
  .then(function (response) {
    console.log(response);
  })
Comment

get request with axios

const axios = require('axios').default;

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}
Comment

axios post request

const createPostRequest = async () => {
	try{
		const { data } = await axios.post(url, body_data, {
		   headers: {
	    	 'Authorization': `Basic ${token}`
		   },
		})
    
	    console.log(data)
	} catch (error) {
		console.log(error)
	}
}

createPostRequest();
Comment

axios response.json

const axios = require('axios');

const res = await axios.get('https://httpbin.org/get', { params: { answer: 42 } });

res.constructor.name; // 'Object', means `res` is a POJO

// `res.data` contains the parsed response body
res.data; // { args: { answer: 42 }, ... }
res.data instanceof Object; // true
Comment

how to make a post request from axios

import axios from 'axios';

async makeRequest() {
  try {
    const response = await axios.post('your_request_url_here', {
    // Enter your body parameters here
    });
  }
  catch(e) {
    // Handle your error here
  }
}

// Axios returns a promise and hence you can use .then(), .catch for error
// handling if you don't want to use async/await(use try/catch for error 
// handling)
Comment

axios post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  
 #Performing multiple concurrent requests
  function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });
Comment

axios all methods

import React, { useEffect, useState } from 'react'
import axios from 'axios';



const Dashboard = () => {
    const [api, setapi] = useState([]);
    const [flag, setflag] = useState(true);

    const show = async () => {

        const res = await axios.get(`https://crudcrud.com/api/7cd119b8cdd546c5bcd621492ea74cae/article`)
        setapi(res.data)
        console.log(api);
    }

    const dele = async (id) => {

        await axios.delete(`https://crudcrud.com/api/7cd119b8cdd546c5bcd621492ea74cae/article/${id}`)
        setflag(!flag)
    }
    const additem = async()=>{
        const value = prompt("Enter the new value")
        const titleValue = prompt("Enter the add Title value")

        const article ={"name":value,"title":titleValue}

        await axios.post(`https://crudcrud.com/api/7cd119b8cdd546c5bcd621492ea74cae/article`,article)
        setflag(!flag)
    }
    const udate= async(id)=>{
        const data = prompt("Enter the data you wanna update")
        const title = prompt("Enter the title you wanna update")

        await axios.put(`https://crudcrud.com/api/7cd119b8cdd546c5bcd621492ea74cae/article/${id}`,{"name":data,"title":title})
        setflag(!flag)
    }

    useEffect(() => {
        show()
    }, [flag]);
    useEffect(() => {
        show()
        // additem()
    }, []);
    return (
        <>
                <button className='btn btn-primary mr-2' onClick={additem} >Add
                                    </button>
            {/* <h1>hello</h1>
            <button onClick={getdata}>click me</button> */}
            <table className="table">
                <thead>
                    <tr>
                        <th scope="col">User id</th>
                        <th scope="col">Name</th>
                        <th scope="col">Title</th>
                    </tr>
                </thead>
                {api.map((val) => {
                    return (<>
                        <tbody>
                            <tr>
                                <td>{val._id}</td>
                                <td>{val.name}</td>
                                <td>{val.title}</td>

                                <td>
                        
                                    <button className='btn btn-primary' onClick={()=>udate(val._id)} >edit
                                    </button>
                                    <button className='btn btn-danger ml-2' onClick={()=>dele(val._id)}>delete</button>
                                </td>
                            </tr>
                        </tbody>
                    </>)
                })}
            </table>
        </>
    )
}

export default Dashboard
Comment

axios post request

import axios from "axios";
/// POST REQUEST
addCity(data)
  .then((res) => {
      console.log(res);
      alert("success");
	});

export function addCity(data = {}) {
  // console.log(data);
  // {name: "mysore", population: 11111, country: "India"}
  return axios.post("URL", {
    name: data.name,
    population: data.population,
    country: data.country
  });
}
Comment

axios api example

npm i axios
import axios

axios.get("https://catfact.ninja/fact").then((res) => {
    console.log(res.data);
  });
Comment

axios post method

const onSubmit = async (FormData) => {
  FormData.bFlats = meters;
  try {
    let res = await axios({
      method: 'post',
      url: 'http://localhost:5000/api/v1/buildings',
      data: FormData
    });

    console.log(res.data);
    if (res.data.status === 'success') {
      alert("Successfully Inserted");
      reset();
    }
  } catch (error) {
    console.log(error.response.data.message); // this is the main part. Use the response property from the error object
  }
}
Comment

axios api get request

import axios from 'axios';
axios.get('/user_login', {
	params: {
		username: 'john1904',
	}
})
.then(function (response) {
	console.log(response);
})
Comment

axios post

try {
			const response = await axios.post('https://movie-app-3073.herokuapp.com/login/', {
				Username: username,
				Password: password
			});
			const data = response.data;
			props.onLoggedIn(data);	
		} catch (error) {
			console.log('This user cannot be found');
		}
Comment

axios basic methods

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Comment

axios put request

const res = await axios.put('https://httpbin.org/put', { hello: 'world' });

res.data.headers['Content-Type']; 
Comment

Send Data Using Axios


import Axios from "axios";

var res = await Axios.post('/search', {searchTerm: 'searchTerm'});
Comment

axios get request

const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();
Comment

axios request method

Request method aliases
For convenience aliases have been provided for all supported request methods.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE
Comment

axios post request

add.post("http://localhost:5000/add-product")
Comment

axios instance method

Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])
Comment

PREVIOUS NEXT
Code Example
Javascript :: js initialize array with values 
Javascript :: array with unique values javascript 
Javascript :: Connect to socket.io node.js command line 
Javascript :: jquery on change on multiple elements 
Javascript :: how to check if input is string javascript 
Javascript :: export component react 
Javascript :: using apis in javascript 
Javascript :: .fetch method 
Javascript :: js every 
Javascript :: react hide element 
Javascript :: google map react search place 
Javascript :: Material-ui account tree icon 
Javascript :: background image not loading from a link react 
Javascript :: inherit javascript 
Javascript :: three.js cube 
Javascript :: js remove last char of string 
Javascript :: jquery datepicker 
Javascript :: async foreach 
Javascript :: how to enable emit on react in vs code 
Javascript :: how to pass basic auth for api in angular 11 
Javascript :: check valid Phonenumbers 
Javascript :: React-redux and redux 
Javascript :: trigger modal after some time react js 
Javascript :: jquery plugin for searchable dropdown 
Javascript :: get attribute js 
Javascript :: javascript escape newline 
Javascript :: empty check on django json field 
Javascript :: react router link with params 
Javascript :: node isfile or isdirectory 
Javascript :: firebase.apps.length 
ADD CONTENT
Topic
Content
Source link
Name
2+5 =