DekGenius.com
JAVASCRIPT
axios get data
import axios from 'axios';
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
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);
});
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
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.
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
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);
}
}
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();
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
});
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
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);
axios post
axios.post('https:sample-endpoint.com/user', {
Name: 'Fred',
Age: '23'
})
.then(function (response) {
console.log(response);
})
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);
}
}
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
axios post request javascript
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();
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];
});
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
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
});
}
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
}
}
axios api get request
import axios from 'axios';
axios.get('/user_login', {
params: {
username: 'john1904',
}
})
.then(function (response) {
console.log(response);
})
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');
}
axios put request
const res = await axios.put('https://httpbin.org/put', { hello: 'world' });
res.data.headers['Content-Type'];
Send Data Using Axios
import Axios from "axios";
var res = await Axios.post('/search', {searchTerm: 'searchTerm'});
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();
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
axios post request
add.post("http://localhost:5000/add-product")
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])
© 2022 Copyright:
DekGenius.com