在Node.js中提供发布请求后,如何重定向到另一个页面? [英] How to redirect to another page after serving a post request in Node.js?
问题描述
我想使用post方法保存用户通过表单提交的数据,然后将其重定向到本地计算机上的另一个html页面,有什么方法可以使用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?
这是表单的html代码:
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>
这是JavaScript文件:
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");
});
我想要的是,在按下提交"按钮之后,将接收到数据并将用户重定向到post_register.html文件.
all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.
推荐答案
我在计算机上测试了以下代码,并且该代码有效.我在发布请求处理程序中添加了res.redirect('/success')
行,并为/success
路径创建了一个处理程序:
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')
})
您可以使用命名选项更改/success
路径.
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
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
success.html
<html>
<head></head>
<body>
<h1>Welcome</h1>
</body>
</html>
这篇关于在Node.js中提供发布请求后,如何重定向到另一个页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!