Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

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

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 achieve this using Node.js or express how do I do that?

Here is the html code for form:

<html>
<head></head>
<body>
    <form action="post_register.html" method="POST">
        university name:<input type="text" name="name" placeholder="University name"><br>
        faculty Username:<input type="text" name="facul" placeholder="faculty username"><br>
        password:<input type="password" name="password" placeholder="password"><br>
        <button >register</button>
    </form>
</body>

and here is the javascript file:

var express = require("express");
var app = express();
var bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));

app.listen(3000);

app.get("/domain_register",function(req,res)
{
  res.sendFile(__dirname+"/domain_register.html");
})

app.post("/post_register",function(req,res)
 {
  console.log(req.body);
  res.end("yes");
});

all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...