HTTP Methods & Axios
HTTP Methods & Axios
Section titled “HTTP Methods & Axios”HTTP Methods
Section titled “HTTP Methods”| Method | Purpose | Example |
|---|---|---|
GET | Retrieve data from DB | Search |
POST | Send data to server, create a resource | Sign up |
PUT | Create or replace a resource | Update profile |
PATCH | Partial update of a resource | Update password |
DELETE | Remove a resource | Delete account |
HTTP Status Codes
Section titled “HTTP Status Codes”1xxInformational: 100-Continue, 101-Switching Protocols2xxSuccess: 200-OK, 201-Created, 204-No Content3xxRedirection: 301-Moved Permanently, 304-Not Modified4xxClient Error: 400-Bad Request, 401-Unauthorized, 403-Forbidden, 404-Not Found5xxServer Error: 500-Internal Server Error, 502-Bad Gateway, 503-Service Unavailable
Ways to Fetch Data in React
Section titled “Ways to Fetch Data in React”fetch()with.then()async/awaitsyntax- Axios library
- Custom hooks
HTTP with fetch()
Section titled “HTTP with fetch()”fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(data => console.log(data));Async/Await
Section titled “Async/Await”const fetchProducts = async function () { const products = await fetch("https://fakestoreapi.com/products"); const productsJSON = await products.json(); setProducts(productsJSON);};HTTP with Axios
Section titled “HTTP with Axios”npm i axiosimport axios from 'axios';
const fetchUsers = async () => { const url = "https://jsonplaceholder.typicode.com/users"; const response = await axios.get(url); setUsers(response.data);};Axios vs fetch()
Section titled “Axios vs fetch()”| Axios | fetch() |
|---|---|
| Built-in XSRF protection | |
Uses data property | Uses body property (must be stringified) |
| Automatic JSON transforms | Two-step process |
| Request timeout & cancellation | |
| HTTP interceptors built-in | |
| Download progress support | No upload progress |
Create Axios Instance
Section titled “Create Axios Instance”import axios from 'axios';const client = axios.create({ baseURL: 'http://jsonplaceholder.typicode.com/' });export default client;
// Usageimport client from 'api.js';client.get('/users');Multiple Requests with Axios
Section titled “Multiple Requests with Axios”const [response1, response2] = await axios.all([ axios.get('https://api.github.com/users/defunkt'), axios.get('https://api.github.com/users/evanphx')]);HTTP Interceptors
Section titled “HTTP Interceptors”HTTP Request -> Interceptor -> Modified Request -> ServerServer -> HTTP Response -> Interceptor -> Modified Response -> ComponentRequest Interceptor:
axios.interceptors.request.use((req) => { req.headers.authorization = "my secret token"; return req;});Response Interceptor:
axios.interceptors.response.use( res => res, err => { if (err.response.status === 404) { throw new Error(`${err.config.url} not found`); } throw err; });Remove an Interceptor:
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});axios.interceptors.request.eject(myInterceptor);Fake REST APIs for Testing
Section titled “Fake REST APIs for Testing”- https://jsonplaceholder.typicode.com/
- https://reqres.in/
- https://fakestoreapi.com/products
- https://api.github.com/users/google
- https://dummyjson.com/products
Create REST API with json-server
Section titled “Create REST API with json-server”npm install -g json-serverjson-server --watch db.json --port=4000Available routes: GET /employees, POST /employees, PUT /employees/:id, DELETE /employees/:id