在 Node.js 中重定向请求
现在我们有了下面所示的 App.js 文件,我们希望一旦用户名称被节点服务器接收,就将用户重定向回 '/'。我们将在名为 username.txt 的文件中存储用户名
初始 App.js 文件 −
const http = require('http');
const server = http.createServer((req, res)=>{
const url = req.url;
if(url === '/'){
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/> <button type="submit">Submit</button> </body>');
res.write('</html>');
return res.end();
}
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> Hello </body>');
res.write('</html>');
res.end();
});
server.listen(3000);我们添加了以下包含重定向的 if 块。
首先使用 const fs = require('fs') 添加文件系统模块。文件系统 fs 模块为我们提供了 writeFile 和 writeFileSync 方法,用于向文件写入内容。目前我们仅向文件写入一个测试值。稍后我们来看看如何从请求中写入值。
首先使用 const fs = require('fs') 添加文件系统模块。文件系统 fs 模块为我们提供了 writeFile 和 writeFileSync 方法,用于向文件写入内容。目前我们仅向文件写入一个测试值。稍后我们来看看如何从请求中写入值。
if(url === '/username' && req.method === 'POST'){
fs.writeFileSync('username.txt', 'test value');
//redirect
res.statusCode=302;
res.setHeader('Location','/');
return res.end();
}Http 重定向状态码是 302。“Location”也是一个在响应中设置的标头。Location 标头指向 url '/'。响应将重定向到此指向。
用户输入输出屏幕

重定向后,我们将回到同一页面,并在项目目录中创建一个文件。

完整的已更新 App.js 文件是 −
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res)=>{
const url = req.url;
if(url === '/'){
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> <form action="/username" method="POST"> <input type="text" name="username"/> <button type="submit">Submit</button> </body>');
res.write('</html>');
return res.end();
}
if(url === '/username' && req.method === 'POST'){
fs.writeFileSync('username.txt', 'test value');
//redirect
res.statusCode=302;
res.setHeader('Location','/');
return res.end();
}
res.write('<html>');
res.write('<head> <title> Hello TutorialsPoint </title> </head>');
res.write(' <body> Hello </body>');
res.write('</html>');
res.end();
});
server.listen(3000);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP