0

我正在使用 fetch 发布一些 url 编码的表单数据,如下所示:

private buy = async () => {
    const { nonce } = await this.state.instance.requestPaymentMethod();

    const formBody = [];
    formBody.push(`${encodeURIComponent("paymentMethodNonce")}=${encodeURIComponent(nonce)}`);

    // @ts-ignore
    const response = await fetch(`http://localhost:4000/checkout`, {
        method: "post",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body: formBody,
    });
}

它适用于忽略,但在这种情况下我应该使用什么类型才能删除忽略?

4

1 回答 1

0

fetchAPI 是 API 的一部分,DOM它被定义为 lib.dom.d.ts.
根据这个定义,body类型定义为:

type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string;

因此,对于 content type 的请求application/x-www-form-urlencoded,您可以使用URLSearchParamsas bodytype:

private buy = async () => {
  const { nonce } = await this.state.instance.requestPaymentMethod();

  const formBody = new URLSearchParams();
  formBody.append('paymentMethodNonce', nonce);

  const response = await fetch(`http://localhost:4000/checkout`, {
    method: "post",
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    body: formBody,
  });
}
于 2018-10-05T03:31:50.503 回答