Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

reactjs - trouble adding athorization in headers using jwt authoriation react js?

im trying to make a authorization with bearer token from my front to my api, in my api all its working i testing all with insmonia, the problem is in the front when i try to add an Authorization in the headers in this way, im using react-redux for the store so and redux-persist for persist for the data persisting and when i try add this

     export function setToken({ payload }) {
      if (!payload) return;
    
      const { token } = payload.auth;
    
      if (token) {
        api.defaults.headers.authorization = `Bearer ${token}`;
      }
    }
   export default all([
    takeLatest('@auth/persist/REHYDRATE', setToken),
    takeLatest('@auth/SIGN_IN_REQUEST', signIn),
    takeLatest('@auth/SIGN_UP_REQUEST', signUp),
  ]);

but when i reload my admin page where i make my httprequests(post/get etc) in the browser its no reciving the authorization in the headers and say createError.js:16 Uncaught (in promise) Error: Request failed with status code 401

    Request URL: http://localhost:3333/notifications
Request Method: GET
Status Code: 401 Unauthorized
Remote Address: [::1]:3333
Referrer Policy: strict-origin-when-cross-origin

RESPONSE HEADERS
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 23
Content-Type: application/json; charset=utf-8
Date: Mon, 11 Jan 2021 00:52:14 GMT
ETag: W/"17-IQ4NhR9c983ggGeU6wL1lrE99jM"
Keep-Alive: timeout=5
X-Powered-By: Express


REQUEST HEADERS
Accept: application/json, text/plain, */
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:3333
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Sec-GPC: 1
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.101 Mobile Safari/537.36

whats im doing wrong? how can i add the authorization with bearer and the token?

HERE IS MY PROJECT REPOSITORY IF HELPS TO UNDERSTAND THE PROBLEM https://github.com/dariocoroneldev/Error

question from:https://stackoverflow.com/questions/65660537/trouble-adding-athorization-in-headers-using-jwt-authoriation-react-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When i add Authorization in to headers outside from my function setToken() anywhere from the app, then it work, but if i do this, i do it like manually just for test, cuze i dont know how to get my token outside the setToken()

const tokentest =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiaWF0IjoxNjEwMzE3NDcwLCJleHAiOjE2OTY2MzEwNzB9.TikP-RQknI5YMVZmirTH69agd2P0zsW5jIHFcK27kO8';

api.defaults.headers.Authorization = `Bearer ${tokentest}`;

now the problem is not more send the authorization, now i dont know how to get my token outside the setToken function that using a actions thats i generated by the react-perssit library, so here my code

 import { takeLatest, call, put, all } from 'redux-saga/effects';
    import { toast } from 'react-toastify';
    import history from '~/services/history';
    import api from '~/services/api';
    import { signInSuccess, signFailure } from './actions';
    
    // const test = api.defaults.headers.Authorization;
    // console.log(test);

      //here it work, but how can i get my token from here?
      //why just working here and not inside my fucntion?

      const tokentest =
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiaWF0IjoxNjEwMzE3NDcwLCJleHAiOjE2OTY2MzEwNzB9.TikP-RQknI5YMVZmirTH69agd2P0zsW5jIHFcK27kO8';

api.defaults.headers.Authorization = `Bearer ${tokentest}`;
    
    export function* signIn({ payload }) {
      try {
        const { email, password } = payload;
    
        const response = yield call(api.post, 'session', {
          email,
          password,
        });
        const { token, user } = response.data;
    
        if (!user.provider) {
          toast.error('usario no es porveedor');
        }

         //but here doe'snt work nothing when i do this
    
         api.defaults.headers.Authorization = `Bearer ${token}`;
    
        yield put(signInSuccess(token, user));
    
        history.push('/admin');
      } catch (err) {
        toast.error('error de autenticacion, verifique sus datos');
        yield put(signFailure());
      }
    }
    
    export function* signUp({ payload }) {
      try {
        const { name, email, password, whatsapp, repeatPassword } = payload;
        yield call(api.post, 'users', {
          name,
          email,
          password,
          whatsapp,
          repeatPassword,
          provider: true,
        });
    
        history.push('/sesion');
      } catch (err) {
        toast.error('error al registarse');
        yield put(signFailure());
      }
    }
       //here not working too
    export function setToken({ payload }) {
      if (!payload) return;
      const { token } = payload.auth;
      console.log(token);
      if (token) {
        api.defaults.headers.Authorization = `Bearer ${token}`;
      }
    }
    
    export default all([
      takeLatest('@auth/persist/REHYDRATE', setToken),
      takeLatest('@auth/SIGN_IN_REQUEST', signIn),
      takeLatest('@auth/SIGN_UP_REQUEST', signUp),
    ]);

why just working here and not inside my fucntion?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...