According to the specification, the token must go in the header Authorization
. To avoid repeating the process you can make a utilitarian function that prepares the requests:
export const $http = (path, { method, query, body }) => {
/* Accept y Content-Type solo son necesarios si vas a trabajar con una API basada en JSON */
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ${localStorage.getItem('token')}',
};
/* URL construction */
let _url = '<URL a tu endpoint>/${path}';
Object.keys(query || {}).forEach((key) => {
_url += '${key}=${query[key]}&';
});
/* Request payload */
const requestBody = {
method: method || 'GET',
headers,
};
if (method === 'POST' || method === 'PUT') {
requestBody.body = JSON.stringify(body);
}
return fetch(_url, requestBody);
};
So you use it in the following way for example:
export const create = async (data) => {
const res = await $http('/users', {
method: 'POST',
body: data,
});
return res.json();
};
Obviously instead of fetch you can use libraries like Axios . In the backend you should only write a middleware for your server that gets the Authorization
header and check if the token exists or is valid.