How to send post data and redirect in node.js?

Member

by lily , in category: Third Party Scripts , a month ago

How to send post data and redirect in node.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , a month ago

@lily 

To send post data and redirect in Node.js, you can use the following code:

  1. First, install the express module by running the following command:
1
npm install express


  1. Create a new Express server:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/submit', (req, res) => {
  const data = req.body;
  // Do something with the data
  
  // Redirect to a new route
  res.redirect('/success');
});

app.get('/success', (req, res) => {
  res.send('Data submitted successfully!');
});

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


  1. In the above code, we have created a POST route /submit that accepts post data and then redirects to the /success route.
  2. Use a form in your HTML file to send the post data to the server:
1
2
3
4
<form action="/submit" method="post">
  <input type="text" name="data" />
  <button type="submit">Submit</button>
</form>


  1. When you submit the form, the data will be sent to the /submit route, and it will then redirect to the /success route where you can display a success message.
  2. Run the server by executing the following command:
1
node app.js


Now you can send post data and redirect in Node.js.