首页 > 解决方案 > 在 react-native 中发送请求标头/授权 axios.post

问题描述

我很难通过我的申请授权。我的 jwt 令牌

export const update_profile = ({
  about,
  birthday,
  birth_location,
  residence_location,
  occupation,
  company_name,
  gender,
  marital_status,
  phone
}) => {
  return dispatch => {
    dispatch(
      {
        type: UPDATE_PROFILE
      }
    )
    const token = AsyncStorage.getItem('@token_jwt')
    let url = "/update_profile"
    Axios.post(`${SERVER}${url}`, {
      headers: {
        "Authorization": `Bearer ${token}`
      },
      "user": {
        "about": about,
        "birthday": birthday,
        "birth_location": birth_location,
        "residence_location": residence_location,
        "occupation": occupation,
        "company_name": company_name,
        "gender": gender,
        "marital_status": marital_status,
        "cellphone": phone
      }
    })
      .then((response) => {
        updateProfileSuccess(dispatch, response)
      })
      .catch((err) => {
        updateProfileError(err, dispatch)
      })
  }
}

这是我的代码,我总是有未经授权的返回,当用户登录时,我的令牌保存在 AsyncStorage 中。

有人能帮助我吗

标签: reactjsreact-nativehttp-headersaxiosjwt

解决方案


使用Axios,需要将标头作为第三个参数(不是第二个)提供。

像这样

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${token}`
}

const data = {
"user": {
        "about": about,
        "birthday": birthday,
        "birth_location": birth_location,
        "residence_location": residence_location,
        "occupation": occupation,
        "company_name": company_name,
        "gender": gender,
        "marital_status": marital_status,
        "cellphone": phone
      }
}

axios.post(`${SERVER}${url}`, data, {
    headers: headers
  })
  .then((response) => {
    ...
  })
  .catch((error) => {
    ...
  })

或者,您可以传递一个应该是对象的参数

...
const options = {
  method: 'POST',
  headers: headers,
  data: data,
  url: `${SERVER}${url}`,
};
axios(options);

推荐阅读