首页 > 解决方案 > 如何在 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"

标签: javascriptreactjstypescriptionic-frameworkaxios

解决方案


您在第二个请求中的设置方式存在问题headers,它需要对象,而不是字符串:

axios
  .post("/xx/cards", partnerData, {
    headers: {
      // Use correct key here which your api expects
      token: firstResponse.data.token,
    }
})


推荐阅读