Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
- Introduction
- A video tutorial
- Installation
- The Axios API
- GET requests
- Add parameters to GET requests
- POST Requests
Introduction
Axios is a very popular JavaScript library you can use to perform HTTP requests, that works in both Browser and Node.js platforms.
It supports all modern browsers, including support for IE8 and higher.
It is promise-based, and this lets us write async/await code to perform XHR requests very easily.
Using Axios has quite a few advantages over the native Fetch API:
- supports older browsers (Fetch needs a polyfill)
- has a way to abort a request
- has a way to set a response timeout
- has built-in CSRF protection
- supports upload progress
- performs automatic JSON data transformation
- works in Node.js
A video tutorial
Check out this video where I create an Express server that offers a POST endpoint, and I make an Axios request to it, to post data:
Installation
Axios can be installed using npm:
npm install axios
or yarn:
yarn add axios
or include it in your page using unpkg.com:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
The Axios API
You can start an HTTP request from the axios
object:
I use
foo
andbar
as random names. Enter any kind of name to replace them.
axios({
url: 'https://dog.ceo/api/breeds/list/all',
method: 'get',
data: {
foo: 'bar'
}
})
but for convenience, you will generally use
axios.get()
axios.post()
(like in jQuery you would use $.get()
and $.post()
instead of $.ajax()
)
Axios offers methods for all the HTTP verbs, which are less popular but still used:
axios.delete()
axios.put()
axios.patch()
axios.options()
and a method to get the HTTP headers of a request, discarding the body:
axios.head()
GET requests
One convenient way to use Axios is to use the modern (ES2017) async/await syntax.
This Node.js example queries the Dog API to retrieve a list of all the dogs breeds, using axios.get()
, and it counts them:
const axios = require('axios')
const getBreeds = async () => {
try {
return await axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = await getBreeds()
if (breeds.data.message) {
console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
}
}
countBreeds()
If you don’t want to use async/await you can use the Promises syntax:
const axios = require('axios')
const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(
`Got ${Object.entries(response.data.message).length} breeds`
)
}
})
.catch(error => {
console.log(error)
})
}
countBreeds()
Add parameters to GET requests
A GET response can contain parameters in the URL, like this: https://site.com/?foo=bar
.
With Axios you can perform this by using that URL:
axios.get('https://site.com/?foo=bar')
or you can use a params
property in the options:
axios.get('https://site.com/', {
params: {
foo: 'bar'
}
})
POST Requests
Performing a POST request is just like doing a GET request, but instead of axios.get
, you use axios.post
:
axios.post('https://site.com/')
An object containing the POST parameters is the second argument:
axios.post('https://site.com/', {
foo: 'bar'
})
Download my free Node.js Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More node tutorials:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js