How to redirect post request to another route in node.js?

by cali_green , in category: Third Party Scripts , 2 months ago

How to redirect post request to another route in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 2 months ago

@cali_green 

In Node.js, you can redirect a POST request to another route by using the res.redirect() method in the route handler function. Here is an example of how you can redirect a POST request to another route:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const express = require('express');
const app = express();

// route for handling the POST request
app.post('/submitForm', (req, res) => {
  // do some processing with the form data
  
  // redirect to another route after processing the form data
  res.redirect('/success');
});

// route for the redirected request
app.get('/success', (req, res) => {
  res.send('Form submitted successfully!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});


In this example, when a POST request is made to the /submitForm route, the server processes the form data and then redirects the request to the /success route. The user will then see the "Form submitted successfully!" message in their browser.