首页 > 解决方案 > 获取多种数据

问题描述

我正在构建一个电子商务网站,我使用 fetch API 将产品详细信息和产品照片从同一个表单获取到同一个 URL。

像这样

await fetch('/host', {

     method: 'POST',
     body: fd

     }).then(

    fetch('/host', {
        
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({

            title: title,
            category: category,
            hostKind: hostKind,
            area: area,
            realstateDesc: realstateDesc,
            neighbourhood: neighbourhood,
            governorate: governorate,
            city: city,
            address: address,
            zipCode: zipCode,
            allowed: allowed,
            maxnum: maxnum,
            timeper: timeper,
            additional: additional,
            price: price,


        })



    })
)

问题是有什么方法可以在相同的获取代码中获取它们。

请注意

1- the body and the headers are different .
2- I use the fetch for photos to fetch to a middleware 

标签: javascriptnode.jsfetch-api

解决方案


在客户端,您可以将多个 Promise 合并为一个。
这可以使用Promise.all() API 来完成。

const options1 = {method: 'POST', body: someData}
const options2 = {method: 'POST', headers: someHeaders, body: anotherData}

const requests = [fetch('/host', options1), fetch('/host', options2)]

const [response1, response2] = await Promise.all(requests)

推荐阅读