javascript - 如何在 Ionic React 应用程序中使用 Axios 将第一个请求响应的令牌传递给第二个请求标头(2 个 Post 请求)
问题描述
我想同时注册一个用户并保存他的合作伙伴的数据。第一个 axios 请求创建用户并返回一个令牌。我需要令牌作为第二个请求的标头。我已经按照“doCreateAccount”实现了,但它不起作用。它只执行第一个请求 .post("xx/register", userData)
有人能告诉我如何发出两个 axios 请求,第二个使用从第一个响应中获取的令牌吗?
组件:
import React from "react";
import { useHistory } from "react-router-dom";
import { useState } from "react";
import axios from "axios";
const CreateAccount: React.FC = () => {
const history = useHistory();
const doCreateAccount = () => {
const userData = {
eMail: getValues("email"),
password: getValues("password"),
};
const partnerData = {
cardType: "6",
firstName: getValues("partnerFirstName"),
lastName: getValues("partnerLastName"),
};
axios
.post("/xx/register", userData)
.then((firstResponse) => {
localStorage.setItem("user", JSON.stringify(firstResponse.data));
axios
.post("/xx/cards", partnerData, {
headers: firstResponse.data.token,
})
.then((secondResponse) => {
history.push("/homePage");
return secondResponse.data;
})
.catch((error) => {
console.log("sth happened in cards request");
setIserror(true);
});
})
.catch((error) => {
console.log("sth happened in register");
setIserror(true);
});
};
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Online Registration</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<form>
<h1>User Data</h1>
<IonItem>
<IonLabel position="floating">E-Mail *</IonLabel>
<IonInput type="email" {...register("email")} />
</IonItem>
{errors.email && <p>{errors.email.message}</p>}
<IonLabel position="floating">
Passwort *
</IonLabel>
<IonInput type="password" {...register("password")} />
</IonItem>
{errors.password && <p>{errors.password.message}</p>}
<h1>Partner card data</h1>
<IonItem>
<IonLabel position="floating">First Name *</IonLabel>
<IonInput
value={partnerFirstName}
{...register("partnerFirstName"}
></IonInput>
</IonItem>
<IonItem>
<IonLabel position="floating">Last Name *</IonLabel>
<IonInput
value={partnerLastName}
{...register("partnerLastName"}
></IonInput>
</IonItem>
<IonButton type="submit">Send</IonButton>
<IonButton onClick={() => history.goBack()} color="danger">
CANCEL
</IonButton>
</form>
</IonGrid>
</IonContent>
</IonPage>
);
};
export default CreateAccount;
"@hookform/resolvers": "^2.4.0",
"react-hook-form": "^7.1.1",
"yup": "^0.32.9"
解决方案
您在第二个请求中的设置方式存在问题headers
,它需要对象,而不是字符串:
axios
.post("/xx/cards", partnerData, {
headers: {
// Use correct key here which your api expects
token: firstResponse.data.token,
}
})
推荐阅读
- java - java中是否有一些用于List、Set和Map的Junit测试用例?
- scala - 确定操作 A 是会话中第一个操作的频率
- angular - Angular Compnent - 类型 '(data: any) => any' 缺少类型中的以下属性
- ios - Xcode TabBarItem 标题未正确更新
- javascript - axios获取请求成功但数据属性为空?
- java - 需要从 ArrayLists 的 ArrayList 中删除元素
- tf.keras - 我们如何从 Keras 中的模型中获取神经元总数?有什么功能吗?
- bash - 使用 Bash 协助转置功能
- list - 在 `(string * int) list` 的列表中查找最大值
- reactjs - 如何在 React 中异步删除错误消息