@lily
To send post data and redirect in Node.js, you can use the following code:
- First, install the express module by running the following command:
- 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');
});
|
- In the above code, we have created a POST route /submit that accepts post data and then redirects to the /success route.
- 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>
|
- 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.
- Run the server by executing the following command:
Now you can send post data and redirect in Node.js.