HTTP Request

Understanding HTTP requests is necessary when it comes to web development. A request is essentially a message that’s sent to a server. The message is structured based on the protocol, HTTP (HyperText Transfer Protocol), and requests for a specific action/method. Once the server receives this request, it sends a response back containing the results or any error messages. There’s A LOT of content in a request and response, so we will only be going through the important ones.

Common HTTP Methods

GET

A GET request asks the server for a specific resource

POST

A POST request sends data to the server, usually to create something in the database (e.g. a form result)

PUT

A PUT requests is used to update existing data on the server

PATCH

A PATCH request is used to modify a sub-part of existing data on the server. This is different than a PUT request in that a PATCH request only updates a portion while a PUT request replaces the whole data

DELETE

A DELETE requests deletes existing data on the server

Axios

We don’t have to get into the nuance of how HTTP requests are sent. With Axios, a Node.js package, we can send requests with their API.

axios({
	method: "get" | "post" | "delete" | "put" | "patch",
	url: "<https://google.com>",
	data?: {
		// data to send in request
	},
	params?: {
		// params to send in request
	},
	...additionalConfigurations
})

Axios Instance

An Axios Instance allows us to make more efficient requests with a base url. When I say efficient, I mean efficient for us, the programmers. We can make requests easier through the instance rather than having multiple Axios calls (like the example above) with the only difference being the method.

Here is a quick example

const axiosInstance = axios.create({
	url: "<https://google.com>"
})

// GET request
axiosInstance.get('/')

// POST request
axiosInstance.post('/', {...data})

Let’s take this a step further and implement the module pattern to abstract Axios away. The module pattern is to encapsulate certain values in a file while only exposing functions to access them. It helps with code reusability a lot!

Here is what it would look like

// user.ts

const UserInstance = axios.create({ url: "<https://user-server>" })

export const getUser = (id) => UserInstance.get(`/${id}`)

export const createUser = (firstName, lastName) => {
	const fullName = `${firstName} ${lastName}`
	return UserInstance.post('/', { fullName })
}

Even though there’s not a lot of difference between the two examples, the 2nd example (using the module pattern), allows for more readability and code reuse. Imagine if you didn’t have a function like createUser(). You would be writing the same code over and over again!

Axios API Usage