简体   繁体   中英

How to pass Token of the first request response to the second request header, using Axios in an Ionic React app (2 Post Requests)

I want to register a user and save his partner's data at the same time. The first axios request creates the user and returns a token. I need the token as a header of the second request. I have implemented as following 'doCreateAccount' but it is not working. It performs only the first request.post("xx/register", userData)

Can someone tell me how to make two axios requests, where the second one uses the token taken from the response of the first one?

The component:

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"

There is a problem with how you setting headers in your second request, it expects object, not a string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM