Redux-Saga将标头传递给axios.post调用

时间:2018-11-10 17:04:16

标签: django reactjs jwt redux-saga

我在redux-saga上遇到了一些困难。我有以下传奇故事:

createPostSaga

function* createPostSaga(action) {
  const token = yield select(selectToken);
  const headerParams = {
    Authorization: `JWT ${token}`
  };
  console.log(token, headerParams);
  try {
    yield call(axios.post, "/posts/", action.payload, headerParams);
    yield call(getPosts());
  } catch (error) {
    console.log(error);
  }
}

如您所见,我正在选择令牌,并将其放入具有键Authorization和值JWT ${token}的对象中,我的API仍在响应401 unauthorized,但它必须是这次通话有问题,因为我可以在邮递员中复制此通话,并且一切顺利:

Postman Request

有人看到我做错了吗?

2 个答案:

答案 0 :(得分:1)

尝试创建提取功能,并在.call内使用它。

function* createPostSaga(action) {
  const token = yield select(selectToken);
  const headerParams = {
    "Authorization": `JWT ${token}`
  };

  const apiCall = () => {
    return axios.post('/posts', {
      action.payload // only if not an object. Otherwise don't use outer {},
    },
    headerParams: headerParams,
   ).then(response => response.data)
    .catch(err => {
      throw err;
    });
  }

  console.log(token, headerParams);
  try {
    yield call(apiCall);
    yield call(getPosts());
  } catch (error) {
    console.log(error);
  }
}

答案 1 :(得分:0)

您必须像这样调用该函数。

function* createPostSaga(action) {
  const token = yield select(selectToken);
  const headerParams = {
    Authorization: `JWT ${token}`
  };
  console.log(token, headerParams);
  try {
    yield call(axios.post, "/posts/", action.payload, {headers:headerParams});
    yield call(getPosts());
  } catch (error) {
    console.log(error);
  }
}