How to redirect to another page after serving a post request in Node.js?

前端 未结 1 2029
梦毁少年i
梦毁少年i 2021-01-18 23:09

I want to save the data submitted by the user through a form using post method and then redirect it to another html page that I have on my local machine, is there any way to

相关标签:
1条回答
  • 2021-01-18 23:26

    I tested below code in my computer and it worked. I added res.redirect('/success') line to the post request handler and created an handler for /success path:

    app.get('/', function (req, res) {
      res.sendFile(__dirname + '/index.html')
    })
    

    You can change /success path with your naming choice.

    App.js

    var express = require('express')
    var app = express()
    var bodyparser = require('body-parser')
    app.use(bodyparser.urlencoded({ extended: true }))
    
    app.listen(3000)
    
    app.get('/', function (req, res) {
      res.sendFile(__dirname + '/index.html')
    })
    
    app.get('/success', function (req, res) {
      res.sendFile(__dirname + '/success.html')
    })
    
    app.post('/register', function (req, res) {
      console.log(req.body)
      res.redirect('/success')
    })
    

    index.html

    <html>
        <head></head>
        <body>
            <form method="post" action="/register">
                <input type="text" name="username">
                <input type="password" name="password">
                <input type="submit">
            </form>
        </body>
    </html>
    

    success.html

    <html>
        <head></head>
        <body>
            <h1>Welcome</h1>
        </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题