首页 > 解决方案 > 在 Node.js 中提供发布请求后如何重定向到另一个页面?

问题描述

我想使用 post 方法通过表单保存用户提交的数据,然后将其重定向到我在本地机器上的另一个 html 页面,有没有办法使用 Node.js 实现这一点或表达我该怎么做?

这是表单的html代码:

<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>

这是javascript文件:

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");
});

我想要的是在按下提交按钮后接收到数据并将用户重定向到 post_register.html 文件。

标签: javascripthtmlnode.jsexpress

解决方案


我在我的电脑上测试了下面的代码,它工作正常。我res.redirect('/success')在 post 请求处理程序中添加了行并为/success路径创建了一个处理程序:

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

/success您可以使用您的命名选择更改路径。

应用程序.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')
})

索引.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>

成功.html

<html>
    <head></head>
    <body>
        <h1>Welcome</h1>
    </body>
</html>

推荐阅读