How to Make POST redirect in -Node Js
To achieve a POST redirect (POST-to-POST) in Node.js using Express, you’ll need to use a combination of client-side JavaScript and server-side routing. Unfortunately, HTTP does not directly support redirecting a POST request to another POST endpoint. However, you can work around this limitation by using a client-side script to perform the second POST request after the initial one is handled.
Here’s a step-by-step guide to achieve this:
Set up the Express server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// Middleware to parse the body of the request
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// POST route for initial form submission
app.post('/submit', (req, res) => {
const data = req.body;
console.log('Received data:', data);
// Send a response that includes a script to perform the second POST request
res.send(`
<html>
<body>
<form id="redirectForm" method="post" action="/thank-you">
<input type="hidden" name="data" value='${JSON.stringify(data)}' />
</form>
<script>
document.getElementById('redirectForm').submit();
</script>
</body>
</html>
`);
});
// POST route for the thank you page
app.post('/thank-you', (req, res) => {
const data = req.body;
res.send('Thank you for your submission! Received data: ' + JSON.stringify(data));
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});Explanation:
- Initial POST Route: The
/submitroute handles the initial POST request. It processes the form data and then sends an HTML response that contains a form with the same data, and a script that automatically submits this form to the/thank-youroute using the POST method. - Second POST Route: The
/thank-youroute handles the second POST request and sends a thank-you message along with the received data.
Testing: You can test this setup by sending a POST request to /submit using an HTML form or a tool like Postman. The server will handle the request and then automatically redirect to the /thank-you route with a POST request.
Here’s an example HTML form to test the initial POST request:
<!DOCTYPE html>
<html>
<head>
<title>POST Redirect Example</title>
</head>
<body>
<form action="/submit" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>Save this HTML in a file (e.g., index.html), serve it from your server, or open it directly in your browser to test the flow.
