21xrx.com
2025-07-08 13:35:39 Tuesday
文章检索 我的文章 写文章
Node.js POST 实现页面跳转
2023-07-09 22:19:08 深夜i     22     0
Node js POST 页面跳转

Node.js是一种开源、跨平台的JavaScript运行环境,可以用于服务器端的开发。它使用事件驱动、非阻塞I/O模型,能够高效地处理大规模的并发请求。

在Node.js中,我们可以使用HTTP模块来创建一个Web服务器。通过HTTP模块,我们可以实现GET和POST两种不同的请求方式。其中,GET请求用于从服务器获取数据,而POST请求则用于向服务器提交数据。

在本文中,我们将介绍如何使用Node.js实现网页跳转,具体来说,是使用POST请求将数据提交到服务器,并从服务器返回一个新的页面。

首先,我们需要导入HTTP模块并创建一个服务器。代码如下:

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
 res.statusCode = 200;
 res.setHeader('Content-Type', 'text/html');
 res.end('<html><body><form method="post" action="/submit"><input type="text" name="username"><input type="submit" value="Submit"></form></body></html>');
});
server.listen(port, () => {
 console.log(`Server running at http://localhost:${port}/`);
});

这里我们创建了一个简单的表单,用于向服务器提交数据。表单包含一个文本框用于输入用户名,并有一个提交按钮。

接下来,我们需要处理POST请求,将提交的数据保存到服务器,并返回一个新的页面。代码如下:

const http = require('http');
const port = 3000;
const server = http.createServer((req, res) => {
 if (req.method === 'POST') {
  let body = '';
  req.on('data', chunk => {
   body += chunk.toString();
  });
  req.on('end', () => {
   const username = body.split('=')[1];
   res.writeHead(301, { Location: '/welcome' });
   res.end();
  });
 } else {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/html');
  res.end('<html><body><form method="post" action="/submit"><input type="text" name="username"><input type="submit" value="Submit"></form></body></html>');
 }
});
server.listen(port, () => {
 console.log(`Server running at http://localhost:${port}/`);
});

在这里,我们使用了POST请求方法,并监听了request对象的data和end事件,将提交的数据保存到body变量中。然后,我们从body中提取出用户名,并将服务器的响应状态码设置为301,同时在响应头中设置Location属性为/welcome,表示跳转到/welcome页面。最后,我们通过res.end()方法结束响应。

到这里,我们就成功地使用Node.js实现了页面跳转。当用户在表单中输入用户名并点击提交按钮时,服务器会收到POST请求,保存用户名数据并跳转到/welcome页面。

  
  

评论区