简体   繁体   中英

How do i pass a bearer authorization token with ApiSauce

Please help check if the method i used to pass the bearer authorization token, because its not working, Maybe im missing something please

apiClient.addAsyncRequestTransform(async (request) => {
  const authToken = await authStorage.getToken();
  if (!authToken) return;
  request.headers["Authorization"] = "access " + authToken;
});

邮递员截图

反应本机调试器

A bearer token normally starts with the phrase bearer . So, replace the word access with bearer and try again:

apiClient.addAsyncRequestTransform(request => async () => {
  const authToken = await authStorage.getToken();
  if (!authToken) return;
  request.headers["Authorization"] = "Bearer " + authToken;
});

Here is my Complete Code:

import apisauce from 'apisauce';
import { Constants } from '../utils/Constants';
import LocalStorage from '../Service/LocalStorage'
let local = new LocalStorage()

export const createBackendServer = (baseURL = Constants.BASE_URL) =>
{
 const api = apisauce.create({
 baseURL,
 timeout: 30 * 1000,
  });

 api.setHeaders({
  Accept: 'application/json',
 'Content-Type': 'application/json',
  })

 api.addAsyncRequestTransform(request => async () => {
  await local.getSession((res) => {
   if (res.token) {
request.headers["Authorization"] = "Bearer " + res.token;
 }
 })
});

 const signUpUser = (body) => api.post('/signup', body);
 const signInWithEmailPassword = (body) => api.post('/login', body);
  const signOut = () => api.get('/logout');

  return {
 signUpUser,
 signInWithEmailPassword,
 signOut
};
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM