javascript - 在 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 文件。
解决方案
我在我的电脑上测试了下面的代码,它工作正常。我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>
推荐阅读
- python-3.x - 保存 matplotlib 图时通过矩形选择保留缩放
- python - 有没有办法在每次迭代时更新 fsolve Python 函数的参数?
- php - 上传图片到服务器修改名称
- javascript - 什么是 JavaScript 运行时?
- amazon-s3 - 从命令式 try-with-resource 转变为反应式 using, using()
- spring-boot - Spring Boot 2.2.6 Java 应用程序在错误的数据库上执行 sql 查询
- stored-procedures - 用于更新超过 1 000 000 行的 Pl/Sql 脚本
- facebook-ads - 如何从 App Store 下载 - 链接到 Facebook 帖子?
- clickhouse - 有没有办法做clickhouse索引和分区分析
- amazon-web-services - 将旧的 tfstate 用于 terraform 破坏目的