【问题标题】:How to pass Token of the first request response to the second request header, using Axios in an Ionic React app (2 Post Requests)如何在 Ionic React 应用程序中使用 Axios 将第一个请求响应的令牌传递给第二个请求标头(2 个 Post 请求)
【发布时间】:2021-07-16 13:09:27
【问题描述】:

我想同时注册一个用户并保存他的合作伙伴的数据。第一个 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"

【问题讨论】:

  • 您的代码看起来不错(除了损坏的 jsx,比如关闭 form 标记,我猜您删除了一些部分),它应该可以工作。你确定你的第一个请求没有抛出错误吗?
  • @Danila,第一个请求没有抛出错误,它创建了用户。第二个请求捕获一个错误:console.log("sth occurred in cards request");
  • 那么,您的第二个请求实际上正在运行,您的应用程序会执行这两个请求。您需要记录错误以了解发生了什么,或检查网络控制台。问题是第二个请求由于某种原因崩溃了
  • 在网络控制台中,我只得到状态成功 201 的 /xx/register,没有别的。感谢您的时间。 :)
  • 嗯,headers: firstResponse.data.token, 那里可能有问题,我认为您需要在那里传递带有一些键的对象,例如headers: { token: firstResponse.data.token }

标签: javascript reactjs typescript ionic-framework axios


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2020-07-21
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2020-06-16
    • 2017-11-20
    相关资源
    最近更新 更多