I need help with server redirection in my React app. My app runs on an Apache web server. I’ve tested redirection with this PHP code:
(redirect.php)
<?php
header('Access-Control-Allow-Origin: *');
$url = "/";
header("Location: $url");
exit;
?>
(index.html)
<form id="redirectForm" action="https://.../redirect.php">
<button type="submit">Submit</button>
</form>
Redirection works fine in a simple HTML form. But in my React app, I need the following:
- Authorization Header: I must send an authorization header with the request.
- POST Method: The request must use the POST method.
- No Visible Form: Using a hidden form with inputs could work, but it doesn’t handle the authorization header.
I want to avoid client-side redirection. For example, I know I could check the response, and if the status code is 302, get the new location from the header and redirect the client manually. However, I think this is not secure enough. This is especially important because I’m redirecting to a payment gateway, which needs to be handled very carefully.
How can I achieve this in a React app? Any advice or examples would be very helpful.
this is what I have implemented in my react app
const apiUrl = "https://.../serverRedirect.php";
const paymentRedirect = ({ token, body }) => {
fetch(apiUrl, {
body: JSON.stringify(body),
headers: {
// I tried "application/json" in the front-end and the back-end too
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${token}`,
},
method: "POST",
});
};
export default paymentRedirect;