reactjs - 在 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 中。
有人能帮助我吗
解决方案
使用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);
推荐阅读
- android - 如何在单击按钮时删除 recyclerview 的 ckeck 框选中项?
- python - 从具有相同索引的矩阵生成列表
- armadillo - 当我将犰狳链接到 clblas 时未定义的符号 _zgemm_
- android - 从一台设备向另一台设备发送推送通知
- docker - 安装 docker 客户端和 docker 组合在一个 docker 文件(Node js 应用程序)中
- ruby - 如何处理 XML 响应。获取元素数据失败
- firebase-authentication - Ionic4:电子邮件无密码身份验证 - 用户未注册
- python - Pandas:重塑和组合数据
- javascript - 如何创建具有多种状态的按钮?
- c++ - 从 char* 中提取 '\r' 之前的所有字符