I have an API Gateway endpoint backed by lambda function, as part of that I am returning a redirect to my caller. But in browser what I see is that after POST request, browser sees a 303 response, and then makes a get request to the redirected url (in the network tab), but doesnt actually redirect. i.e. the browser remains on the page via which I had made the initial post request.
Details below
POST ENDPOINT
def lambda_handler(event, context):
DOMAIN = 'https://<my_Api_gateway_address'
response = {
"headers": {"Location": DOMAIN+'/success', },
"statusCode": 303,
}
return response
Below is the APIGateway’s LAmbda Integration
Below is the javascript code that makes the initial POST request
var url = "https://<my_Api_gateway_endpoint>";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Handle the response here if needed
console.log(xhr.responseText);
}
};
xhr.send(formData);
What do i need to do here to actually redirect to the redirected location on post request?
— UPDATE —
I’ve updated my client side javascript code to below
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
console.log(xhr.responseText);
console.log(xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log("DONE");
}
};
xhr.send(formData);
Below is the snippet of browser console logs.
2
Answers
Just set the value of the
window.location.href
Alternatively, you can just change the response structure of your Lambda so that it would send back
200
and the URL of the payment gateway’s checkout page. By doing this, you will be able to simplify the implementation of your client-side code:The initial request is an AJAX request which follows the redirect automatically (you cannot prevent that, even if you want to). But that has nothing to do with the location of the current browser window. You have to set that manually once the request is finished. You should be able to get the final url with
xhr.responseURL
But just as a remark, this whole process seems a bit fishy. Ie you are doing an AJAX post and then redirecting your browser to the resulting URL of that POST. What if that call requires any special headers? You won’t be able to set them.