My RESTful service allows batching requests.
I’m trying to combine requests into one batch with help of Fetch API:
let req1 = {
url: "/cups/count",
options: {
method: 'GET',
headers: {
'Content-Type': 'application/http'
}
}
},
req2 = {
url: "/spoons/count",
options: {
method: 'GET',
headers: {
'Content-Type': 'application/http'
}
}
},
authToken = "Bearer my_token123",
batchUrl = "http://something.com/batch",
options = {
method: 'POST',
headers: {
'Authorization': authToken,
'Content-Type': 'multipart/mixed'
},
body: {req1, req2}
};
return fetch(batchUrl, options)
.then(response => response.json())
.then(items => dispatch(batchSuccess(items)))
.catch((err) => {
console.log(err)
});
However it returns an error – bad request. I suppose I may combine HTTP requests in wrong way.
Is there simpler way of doing this?
Where in Network Chrome Dev Tools can I see nested HTTP requests?
Advertisement
Answer
Your code does not work because it does not follow multipart/mixed
request format:
- In
Content-Type
header, there is no boundary information. - The child requests are not divided by boundary, instead they will be sent as plain text of req1 & req2 object.
In order to send valid multipart/mixed
request, there is a node.js module batchelor. According to the introduction page, its usage is pretty simple.
If you want to send multipart/mixed
request from browser, you can use build tool (gulp, webpack etc.) to compile batchelor into something like “batchelor-compiled.js” and import it in HTML.
For developer tool, I didn’t find anything in Chrome, but the child requests are visible in Firefox debug window’s “Params” tab.