如何发送带有 formData 的正文作为获取键 api

How to send body with formData inside as a key fetch api

当我尝试将图像和路径发送到 Api 时,它发送的方式类似于 [object Object]

export async function uploadImageToCDN(image: FormData, directory: string = 'dir'): Promise<any> {
const token = await authoriseInApi()

const headers = []
headers.push(['Authorization', `Bearer ${token}`])

const data: Content = new Content('multipart-file', {
    file: image,
    dir: directory
})
return post<any>('https://test-api.test.com/files/upload', data, headers)

}

这就是我收集数据并发送到 Api 的方式:

const formData = new FormData()

    const imageBase64 = await getBase64(file)
    const imageUri = dataURIToBlob(imageBase64)

    formData.append('image', imageUri)

    const res = uploadImageToCDN(formData)

什么是错误?

您需要使用JSON.stringify(data)发送对象参数:

return post<any>('https://test-api.test.com/files/upload', JSON.stringify(data), headers)

或者,如果您想使用 fectch,请尝试同样的操作:

//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})

我写了 xhr 请求,一切正常。

这是我的要求:

export async function uploadImageToCDN(formData: FormData): Promise<ICDNUploadResponse> {
return new Promise(async (resolve, reject) => {
    const token = await getApiTokenByScope('scope')

    const xhr = new XMLHttpRequest()

    xhr.open('post', '/api/test/files/upload')
    xhr.responseType = 'json'
    xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    xhr.onload = async () => {
        if (xhr.status === 401) {
            await refreshApiTokenByScope('scope')
                .then(() => {
                    uploadImageToCDN(formData)
                })
        }
        resolve(xhr.response)
    }
    xhr.onerror = () => {
        reject(xhr.response)
    }
    xhr.send(formData)
})

}