Reputation: 1269
As title. I'm very new to this topic so I will use the example to describe what I want to achieve:
?token=DSKLFJOS...
.fetch
API to try to get the token from 302, and append it to the URL of the (redirect) request ?token=...
so that the second request will get 200.My thought: Maybe this can be achieved after I learn more about the credentials
and/or redirect
options of the fetch
API. But I'm not sure on this!
This is the current code that will fail with 404(on the second request). It is not written by me, so I don't understand it. (and sorry that I cannot post the full code since it's a private content)
fetch(filePath)
.then(response => response.arrayBuffer())
.then(arrayBuffer => callback(arrayBuffer, arrayBuffer.byteLength));
Thanks for your reading. If I any of my idea is incorrect please feel free to correct me and post it as an answer!
Upvotes: 1
Views: 973
Reputation: 171
Maybe something like this will work. Basically, you just check the status code, and if it's 302 you will re-fetch the response with the token, then if the status is still greater than 300 you return null, if not you return the JSON response.
async function getImage(url, token) {
let response = await fetch(url);
// You can also say if (response.status >= 300 && response.status < 400)
if (response.status === 302) {
response = await fetch(`${url}?token=${token}`);
}
if (response.status >= 300) {
return null;
}
return response.json();
}
Whit the headers location would be something like this:
async function getImage(url) {
let response = await fetch(url);
if (response.status === 302) {
response = await fetch(`${url}?token=${response.headers.get('location')}`);
}
return response.json();
}
I remove the second if just to simplify the answer and just having in mind the request would be successful.
Upvotes: 2
Reputation: 791
You can make another request with the new URL with fetch(originalResponse.url + token)
.
The
url
read-only property of the Response interface contains the URL of the response. The value of theurl
property will be the final URL obtained after any redirects.
from https://developer.mozilla.org/en-US/docs/Web/API/Response/url
Here's an example:
let token = "abcdef"
fetch("page-that-redirects.com/")
.then(response => {
if (response.status === 404) {
fetch(response.url + "?token=" + token)
.then(/* do something */)
}
})
// Or with async/await:
let response = await fetch("page-that-redirects.com/")
if (response.status === 404) {
let newResponse = await fetch(response.url + "?token=" + token)
/* do something */
}
Upvotes: -1