How to get the token from response?

770 Views Asked by At

I'm relatively new in this environment. I use "Ant design pro 4" with React and Typescript for a new project.

I call successful my IdentityServer 4 for a token for a login. I see my response in my Browser.

token

status

But how get the token in my code?

import { Reducer } from 'redux';
import { Effect } from 'dva';

export interface StateType {
  status?: 'ok' | 'error';
  jsonRes: string;
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    // status: undefined,
    jsonRes: '',
  },

  effects: {
    * login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);

      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,

        jsonRes: payload.json, //not work
      };
    },
  },
};

export default Model;

EDIT: Maybe that's helpful.

export async function accountLogin(params: LoginParamsType) {
  const sendData = `grant_type=password&username=${params.userName}&password=${params.password}& ........`; 
  const retValue = request('https://localhost:44308/connect/token', {
    method: 'POST',
    data: sendData,
    mode: 'no-cors',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'string',
  });
  return retValue;
}
2

There are 2 best solutions below

0
On

I'm sure you had it figured it out by now, but here it goes anyways

reducers: {
    changeLoginStatus(state, { payload }) {
      return {
        ...state,

        jsonRes: payload.access_token, //<--this should do it
      };
    },

when you call const response = yield call(accountLogin, payload); it gets you the output you see in debug window.

Hope that helps.

3
On

use payload.json().It will read the response stream to completion and parses the response as json.