用 javascript 中的对象包装响应数据

wrap a response data with object in javascript

我有一个组件可以进行 POST 网络调用。组件是:

import { ErrorMessage, Field, Formik, FormikHelpers } from "formik";
import { Button } from "../../../common/ui/Button";
import * as yup from "yup";
// import { RadioSwitch } from "@components/common/RadioSwitch";
import { addPersonalInfo } from "@request/profile";
import { toast } from "react-toastify";

type FormValues = {
  division: string;
  district: string;
  thana: string;
  house: string;
  // same_address: boolean;
};

type IReqBody = {
  division: string;
  district: string;
  thana: string;
  house: string;
  // same_address: boolean;
};

const initialValues: FormValues = {
  division: "",
  district: "",
  thana: "",
  house: "",
  // same_address: false,
};

const AddPersentAddressSchema = yup.object({
  division: yup.string().required("Division is required"),
  district: yup.string().required("District is required"),
  thana: yup.string().required("Thana is required"),
  house: yup.string().required("House is required"),
});

export const AddPersentAddressForm = ({
  close,
}: {
  close: () => void;
}): JSX.Element => {
  const handleSubmit = async (
    values: FormValues,
    actions: FormikHelpers<FormValues>
  ) => {
    actions.setSubmitting(true);
    const {
      division,
      district,
      thana,
      house,
      // same_address,
    } = values;
    const reqbody: IReqBody = {
      division: division,
      district: district,
      thana: thana,
      house: house,
      // same_address: same_address,
    };

    try {
      const res = await addPersonalInfo(reqbody);
      if (res.status == 201) {
        toast.success("Your request is being processed");
        actions.setSubmitting(false);
        close();
      } else {
        actions.setSubmitting(false);
      }
    } catch (err) {
      toast.error("Failed to Add Present Address");
      actions.setSubmitting(false);
    }
  };

  return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={AddPersentAddressSchema}
    >
      {(formikBag) => (
        <form onSubmit={formikBag.handleSubmit}>
          <div className="p-6">
            <h3 className="mb-6">Add Present Address</h3>

            <div className="mb-4">
              <label className="space-y-2">
                <p>Division *</p>
                <Field
                  type="text"
                  className="form-input"
                  name="division"
                  placeholder="Dhaka"
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component="p"
                  name="division"
                />
              </label>
            </div>

            <div className="mb-4">
              <label className="space-y-2">
                <p>District *</p>
                <Field
                  type="text"
                  className="form-input"
                  name="district"
                  placeholder="Dhaka"
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component="p"
                  name="district"
                />
              </label>
            </div>

            <div className="mb-4">
              <label className="space-y-2">
                <p>Thana *</p>
                <Field
                  type="text"
                  className="form-input"
                  name="thana"
                  placeholder="Dhanmondi"
                />
                <ErrorMessage
                  className="text-xs text-red-500"
                  component="p"
                  name="thana"
                />
              </label>
            </div>

            <div className="mb-4">
              <div>
                <label className="space-y-2">
                  <p>House/Road/Village *</p>
                  <Field
                    name="house"
                    as="textarea"
                    className="form-textarea"
                    placeholder="Aa"
                  />
                </label>
              </div>
            </div>

            {/* <div className="mb-4">
              <div className="flex justify-between">
                <label className="space-y-2">
                  <p>Same as Permanent Address</p>
                </label>
                <RadioSwitch
                  isChecked={false}
                  // eslint-disable-next-line @typescript-eslint/no-empty-function
                  onChange={() => {}}
                />
              </div>
            </div> */}

            <div className="flex justify-end">
              <Button
                type="button"
                onClick={() => close()}
                size="sm"
                variant="text"
                style={{ marginRight: 12 }}
              >
                Cancel
              </Button>

              <Button
                type="submit"
                size="sm"
                variant="primary"
                isLoading={formikBag.isSubmitting}
                disabled={formikBag.isSubmitting}
                style={{ marginRight: 12 }}
              >
                Save
              </Button>
            </div>
          </div>
        </form>
      )}
    </Formik>
  );
};

如果我进行此网络调用,请求负载为:

{
    "division": "Dhaka",
    "district": "DHAKA-NORTH",
    "thana": "Dhanmondi",
    "house": "Manama Tower"
}

这里是网络调用函数:

export async function addPersonalInfo(reqbody: any) {
  try {
    const apiUrl = `${process.env.EJOB}/api/v1.0.0/applicants/applicant/profile/`;
    const res = await axios.post(apiUrl, reqbody, {
      headers: {
        Authorization: "Bearer " + getTokenFromCookies(), //the token is a variable which holds the token
      },
    });
    return Promise.resolve(res);
  } catch (error) {
    return Promise.reject(error);
  }
}

API 需要像这样的有效响应格式:

{
"permanent_address": {
    "house": "Manama Tower",
    "division": "dhaka",
    "district": "dhaka",
    "thana": "dhanmondi"
    }
}

我试图用 {permanent_address:{req}} 结束最终响应正文,但似乎没有任何效果。我应该更改什么以便使用此代码发出有效请求?

因为您将 IReq 的类型传递给这一行,它没有您想要的结构:

const res = await addPersonalInfo(reqbody);

您可以更改此行以添加新变量,然后尝试:

const temp = {permanent_address:reqbody};
const res = await addPersonalInfo(temp);

const reqbody =  { "house": "Manama Tower", "division": "dhaka", "district": "dhaka", "thana": "dhanmondi" };
const temp = {permanent_address:reqbody};
console.log(temp)

那么它应该可以工作了。

你也可以查看 jsfiddle