Fetch, Axios, Supertest, Express cheat sheet
Differences between Fetch, Axios, Supertest, and Express
Fetch, Axios, Supertest, and Express have slight differences in their API. I will list out a few here for reference.
Axios
Axios uses the data
instance variable.
// client.js
const resp = await axios.get('/pets/1');
const json = resp.data;
Axios can take a post body as its second argument.
// client.js
const postData = {species: 'dog', name: 'Rex'};
const resp = await axios.post('/pets', postData);
Fetch
Fetch uses the json()
method on Response.
// client.js
const resp = await fetch(url, {
method: 'POST',
body: JSON.stringify(postData)
})'
const json = await resp.json();
Supertest
Supertest uses the body
instance variable.
// server.test.js
const supertest = require('supertest');
const request = supertest(app);
...
test('get users', async () => {
const response = await request
.get('/users')
.set('Accept', 'application/json')
expect(response.body).toEqual(jsonObj);
});
To send body data it uses send
on the post
or put
request.
...
const response = await request.post('/api/v1/todos')
.set('Accept', 'application/json')
.send({ text: 'sample', difficulty: 1, assignee: 'John', complete: false });
...
Express
Express reads in json data from req.body
. Just be sure to use
the express.json()
middleware.
It can send json with res.json()
.
app.use(express.json());
...
async function handleCreate(req, res) {
let obj = req.body;
let newRecord = await req.model.create(obj);
res.status(201).json(newRecord);
}
Mock Service Worker
The Mock Service Worker API follows Express closely. There are a few differences.
Use the ctx object for return values.
Use await req.json()
or await req.text()
to get the body of a POST or PUT request.
rest.post(server + "/tasks", async (req, res, ctx) => {
const task = await req.json();
return res(ctx.status(201), ctx.json(task));
}),
Axios setup
Axios has a lot of setup options. One is to set up Bearer Authorization. The following will return an axios instance that always sends the token
and prepends baseURL to when it sends requests.
import axios from 'axios';
export function axiosWithBearer(token) {
const apiInstance = axios.create({
baseURL: API_URL,
});
apiInstance.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return apiInstance;
};