Reputation: 153
I'm building an e-commerce website and I use fetch API to fetch the product details and the product photos from the same form to the same URL .
like so
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,
})
})
)
the question is there any way to fetch them in same fetch code .
notice that
1- the body and the headers are different .
2- I use the fetch for photos to fetch to a middleware
Upvotes: 0
Views: 3368
Reputation: 3647
Adding the image as a base64 encoded String inside your server side script, will allow it to pass it in a JSON object.
You can then set the image on the reply with something similar to:
document.getElementById("imagePlaceholder").src =
`data:image/jpeg;base64,${reply.base64imageString}`);
On the server side you could modify the requests into an array-like parser and then reply to every request in the same order. This would allow you to easily handle multiple requests at once.
Example Client Side:
fetch("/host", {
...,
body: [photoRequestStuff, dataRequestStuff]
}).then(data => {
data.forEach((dataset, index) => {
// index 0 should now be the picture and index 1 the data stuff.
})
})
Upvotes: 0
Reputation: 5061
On the client-side, you can join multiple promises into one.
This can be done using 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)
Upvotes: 1