在reactjs中使用json输入字段发布api请求

问题描述 投票:0回答:1

我的表单包含三个输入字段,以下是键和值类型:

我已经设计了表单,但是如何以对象类型发送gcloud字段键值? gcloud 输入字段的代码:

<label>gcloud keyfile json</label>
  <TextareaAutosize
    name="gcloud_keyfile"
    type="text"
    id="gcloud_keyfile"
    value={values.gcloud_keyfile}
    onChange={handleChange}
  />

  

对于表单提交,我使用了formik,代码如下所示:

const initialValues = {
    organ: "",
    env: "",
    gcloud_keyfile: "" ,
  };

  const { values, errors, touched, handleBlur, handleChange, handleSubmit } =
    useFormik({
      initialValues,
      validationSchema: GcpSchema,
      onSubmit: async (values, action) => {
        try {
          let response = await axios.post(
            `${state.baseUrl}accounts/gcp/`,
            {
              organization: values.organ,
              environment: values.env,
              gcloud_keyfile_json: JSON.stringify(values.gcloud_keyfile),
            });
          if (response.status === 200) {
            setMsg("You Are Successfully Create the Account");
            action.resetForm();
            return Promise.resolve();
          }
        } catch (error) {
          console.error("There was an error!", error);
        }
      },
    });

我使用了 json stringify 但这不起作用

javascript reactjs post axios formik
1个回答
0
投票

我使用了 JSON.parse(gcloud_keyfile_json) 将字符串转换为对象并对输入字段应用验证以仅获取对象值

© www.soinside.com 2019 - 2024. All rights reserved.