Javascript 获取多种类型的数据
我正在建立一个电子商务网站,我使用FetchAPI将产品详细信息和产品照片从同一表单提取到同一URL 像这样Javascript 获取多种类型的数据,javascript,node.js,fetch-api,Javascript,Node.js,Fetch Api,我正在建立一个电子商务网站,我使用FetchAPI将产品详细信息和产品照片从同一表单提取到同一URL 像这样 await fetch('/host', { method: 'POST', body: fd }).then( fetch('/host', { method: 'POST', headers: { 'Content-Type': 'application/json' }, b
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
在客户端,您可以将多个承诺合并为一个承诺。
这可以使用API来完成
const options1={method'POST',body:someData}
const options2={method:'POST',headers:someHeaders,body:anotherData}
常量请求=[fetch('/host',options1),fetch('/host',options2)]
const[response1,response2]=等待承诺。全部(请求)
将图像作为base64编码字符串添加到服务器端脚本中,将允许它在JSON对象中传递
然后,您可以在回复上设置类似以下内容的图像:
document.getElementById("imagePlaceholder").src =
`data:image/jpeg;base64,${reply.base64imageString}`);
在服务器端,您可以将请求修改为类似数组的解析器,然后以相同的顺序回复每个请求。这将允许您轻松地同时处理多个请求
客户端示例:
fetch("/host", {
...,
body: [photoRequestStuff, dataRequestStuff]
}).then(data => {
data.forEach((dataset, index) => {
// index 0 should now be the picture and index 1 the data stuff.
})
})
您可以对服务器进行编程,使其与一个请求一起返回该数据,是的。这与其说是一个JavaScript
fetch()
问题,不如说是一个“如何正确设计PHP REST服务器”。@RandyCasburn奇怪地认为PHPW为什么要组合请求?@Evert-OMG-是的,完全奇怪。我一定是在我虚弱的头脑里把两个问题混在一起了!无论如何,这显然是一个服务器/端点问题。这并不能回答问题,因为OP询问如何通过一个请求而不是两个请求获取两组数据。@jfriend00公平地说,我认为这个问题可以用几种不同的方式来解释。语法不完美,我也没有“将多个请求组合在一起”。是的,我应该先澄清这个问题