网站搜索

json - 如何从响应中获取令牌?


我在这个环境中相对较新。我在一个新项目中使用 React 和 Typescript 的“Ant design pro 4”。

我称我的 IdentityServer 4 为登录获取令牌是成功的。我在浏览器中看到了我的响应。

但是我如何在我的代码中获取令牌?

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;

编辑:也许那有帮助。

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;
}

答案#1

使用 payload.json()。它将读取响应流直到完成,并将响应解析为 JSON。

答案#2

我相信你现在已经弄明白了,但无论如何还是说一下

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

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

当你调用 const response=yield call(accountLogin, payload); 时,它会得到你在调试窗口中看到的输出。

希望这能帮到你。