You need to enable JavaScript to run this app. NextJS调用Google Docs API报'Must specify at least one request'错误求助
优惠活动
大模型
产品
解决方案
定价
更多

NextJS调用Google Docs API报'Must specify at least one request'错误求助

Google Docs API batchUpdate 返回400错误:"Must specify at least one request"

我用NextJS开发功能,目标是创建Google文档并把API返回的数据插入新文档。当前流程是先创建新文档并获取documentId,再用这个ID调用batchUpdate方法执行insertText操作。这个请求在Google Workspace playground里能正常运行,但实际调用时返回400错误,提示'Must specify at least one request'。

网络请求错误

{
  "error": {
    "code": 400,
    "message": "Must specify at least one request.",
    "status": "INVALID_ARGUMENT"
  }
}

控制台响应

Response { 
    type: "cors", 
    url: "https://docs.googleapis.com/v1/documents/1U3xMrjKO5K4jQp_ppJCBb1qgMehjyQa-eT86Io5ZDeM:batchUpdate", 
    redirected: false, 
    status: 400, 
    ok: false, 
    statusText: "Bad Request", 
    headers: Headers(7), 
    body: ReadableStream, 
    bodyUsed: false 
}
​
body: ReadableStream { locked: false }
​​
locked: false
​​
<prototype>: ReadableStreamPrototype { 
    cancel: cancel(), 
    getReader: getReader(), 
    pipeThrough: pipeThrough(), … 
}
​
bodyUsed: false
​
headers: Headers(7) { "cache-control" → "private", "content-encoding" → "gzip", "content-length" → "125", … }
​​
<entries>
​​
<prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … }
​
ok: false
​
redirected: false
​
status: 400
​
statusText: "Bad Request"
​
type: "cors"
​
url: "https://docs.googleapis.com/v1/documents/1U3xMrjKO5K4jQp_ppJCBb1qgMehjyQa-eT86Io5ZDeM:batchUpdate"
​
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
index.tsx:80:16

相关代码

const { data: session } = useSession();
const [documentId, setDocumentId] = useState<string>('');

useEffect(() => {
  data.forEach((player: any) => {
    console.log(player.name);
  });
}, [data]);

const createDoc = (teamName: string) => {
  const fileName: string = `${teamName}`;

  const requestBody: any = {
    requests: [
      {
        insertText: {
          text: 'THIS IS A  BIG OLD TEST TO SEE IF THIS WORKS YA YEET',
          endOfSegmentLocation: {},
        },
      },
    ],
  };
  const parsedRequest: any = JSON.stringify(requestBody);

  fetch(`https://docs.googleapis.com/v1/documents?title=${fileName}`, {
    method: 'POST',
    //   @ts-ignore
    headers: new Headers({ Authorization: 'Bearer ' + session?.accessToken }),
  })
    .then((res: any) => {
      return res.json();
    })
    .then((val) => {
      console.log(val);
      console.log(val.documentId);
      setDocumentId(val.documentId);
    });
};

const fillOutDoc = () => {
  fetch(
    `https://docs.googleapis.com/v1/documents/${documentId}:batchUpdate`,
    {
      method: 'POST',
      headers: new Headers({
        //   @ts-ignore
        Authorization: 'Bearer ' + session?.accessToken,
        'Content-Type': 'application/json',
      }),
      // @ts-ignore
      payload: JSON.stringify({
        requests: [
          {
            insertText: {
              text: 'asdfjasdf',
              endOfSegmentLocation: {},
            },
          },
        ],
      }),
    },
  )
    .then((res: any) => {
      console.log(res);
    })
    .catch((err) => console.error(err));
};

问题解决

报错的核心原因是fillOutDoc函数里的fetch请求参数错误:你用了payload字段来传递请求体,但标准的Fetch API中应该使用body字段。Google Docs API没有收到你传入的requests数组,所以返回了"Must specify at least one request"的错误。

修改后的fillOutDoc函数:

const fillOutDoc = () => {
  fetch(
    `https://docs.googleapis.com/v1/documents/${documentId}:batchUpdate`,
    {
      method: 'POST',
      headers: new Headers({
        Authorization: 'Bearer ' + session?.accessToken,
        'Content-Type': 'application/json',
      }),
      // 把payload改成body
      body: JSON.stringify({
        requests: [
          {
            insertText: {
              text: 'asdfjasdf',
              endOfSegmentLocation: {},
            },
          },
        ],
      }),
    },
  )
    .then((res) => res.json())
    .then((data) => console.log(data))
    .catch((err) => console.error(err));
};

另外注意createDoc函数里你定义了requestBody但没有在fetch中使用,如果创建文档时需要直接插入内容,需要把body字段也加上(不过创建文档的API本身不需要requests,创建后再更新是你当前的流程,所以这部分可以忽略)。

内容的提问来源于stack exchange,提问作者Matthew Dwyer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 10:10:14