【问题标题】:Sending request headers / authorization axios.post in react-native在 react-native 中发送请求标头/授权 axios.post
【发布时间】:2020-08-16 15:50:26
【问题描述】:

我在通过我的申请授权时遇到困难。 我的 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 中。

谁能帮帮我

【问题讨论】:

    标签: reactjs react-native http-headers axios jwt


    【解决方案1】:

    对于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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 2019-05-29
      • 2020-01-06
      • 2018-01-27
      • 2022-10-16
      • 1970-01-01
      相关资源
      最近更新 更多