Graphcms 文件上传 400 错误请求

时间:2021-03-08 22:57:58

标签: graphql

我正在尝试使用 graphcms 和此处提供的文档上传文件: https://graphcms.com/docs/content-api/assets

这是我暂时的句柄提交功能。我只是想记录响应:

async function handleSubmit(event) {
        event.preventDefault();

        const response = await fetch(`${process.env.GRAPHQL_URL_ENDPOINT}/upload`, {
            method: 'POST',
            headers: {
              Authorization: `Bearer ${process.env.BEARER_TOKEN}`,
              'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `fileUpload=${fileUpload.files[0]}`,
          });
        
          console.log(response);
      }

我已经确认 fileUpload.files[0] 是一个文件对象。我得到这个回应: Response { type: "cors", url: "https://api-us-west-2.graphcms.com/v2/cklvg9qoslthv01xi4wou54sk/master/upload", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }

1 个答案:

答案 0 :(得分:0)

我认为您需要在 file 中附加 formData,然后在 body 中传递它。这是一个工作示例

const handleUpload = (file: SelectedFile) => {
    const formData = new FormData();
    formData.append("fileUpload", file);
    fetch(`GRAPHQL_URL_ENDPOINT/upload`, {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((result: Asset) => {
        console.log("Success:", result);
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };