使用 javascript 中的 api 将表单数据发送到服务器

时间:2021-04-27 02:27:59

标签: javascript forms api

我的任务是制作一个表单以将 Excel 文件和消息发送到服务器,我有一个 邮递员收集文件,其中包含以下对象数组:

"formdata": [
             {
                "key": "message",
                "value": "hello",
                "type": "text"
             },
              {
                "key": "users",
                "type": "file",
                "src": "path-to-.xlsx"
              }
            ]

这是我的简单表格:

<div class="landing">
    <div class="intro-text">
      <div class="form-style-3">
        <form id="msgform" method="POST">
          <fieldset>
            <legend>Message</legend>
            <label for="file">
              <span>File
                <span class="required">*</span>
              </span>
              <input type="file" name="file" id="input"
                accept="..csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
            </label>
            <label for="message">
              <span>Message
                <span class="required">*</span>
              </span>
              <input name="message" id="message" type="text" />
            </label>
            <label>
              <input type="submit" value="Submit" />
            </label>
          </fieldset>
        </form>
      </div>
    </div>
  </div>

这是我的 API 连接函数:

const url = 'path-to-api-url';
const form = document.getElementById('msgform');

form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = new FormData(form);

  const formDataSerealized = Object.fromEntries(formData);
  console.log(formDataSerealized);

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: JSON.stringify(formDataSerealized),
      headers: {
        'Content-type': 'application/json',
      },
    });
    const json = await response.text();
    console.log(json);
  } catch (e) {
    console.error(e);
  }

});

我的问题是提交时我在控制台中出现此错误

{"errors":[{"message":"message not found"}]}

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您应该调整代码以不对内容使用 JSON 格式。如果您在没有 JS 的情况下发布表单,则将使用这种编码。

form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = new FormData(form);

  const formDataSerealized = Object.fromEntries(formData);
  console.log(formDataSerealized);

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: formDataSerealized,
      headers: {
        'Content-type': 'multipart/form-data',
      },
    });
    const json = await response.text();
    console.log(json);
  } catch (e) {
    console.error(e);
  }
});

EDIT 如果您在表单提交中发送文件,请改用内容类型 multipart/form-data