5

我正在尝试制作一个带有用户名和姓氏的简单表单,当用户提交信息时,会显示另一个页面。我在html中做了一个表格,但我不确定接下来要做什么?有没有人有一个小的、独立的表单示例,使用node js

4

1 回答 1

12

此示例并未完全完成您的任务。但它是一个自包含的 node.js 程序,在收到表单时会显示一个表单和一个不同的页面。

将其复制到文件中,然后运行node filename.js,然后http://localhost:3000在浏览器中访问。

注意异步代码结构。我定义了一个handler函数,但不立即执行它。相反,我们将函数传递给http.createServer然后调用.listen(3000). 现在,当一个 HTTP 请求进来时,http 服务器会将一req, res对传递给处理函数。req是请求对象(这将包含表单数据;有关如何获取该数据的一些提示,请参阅此问题。(我建议您直接进入并构建一个小型 Express 应用程序。这是一个非常好的框架。)

//app.js
// Load the built in 'http' library
var http = require('http'); 
var util = require('util');

// Create a function to handle every HTTP request
function handler(req, res){
  if(req.method == "GET"){ 
    console.log('get');
    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200);
    res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
  } else if(req.method == 'POST'){
    console.log('post');
    // Here you could use a library to extract the form content
    // The Express.js web framework helpfully does just that
    // For simplicity's sake we will always respond with 'hello world' here
    // var hello = req.body.hello;
    var hello = 'world';
    res.setHeader('Content-Type', 'text/html');
    res.writeHead(200);
    res.end("<html><body><h1>Hello "+hello+"!</h1></body></html>");
  } else {
    res.writeHead(200);
    res.end();
  };
};

// Create a server that invokes the `handler` function upon receiving a request
// And have that server start listening for HTTP requests
// The callback function is executed at some time in the future, when the server
// is done with its long-running task (setting up the network and port etc)
http.createServer(handler).listen(3000, function(err){
  if(err){
    console.log('Error starting http server');
  } else {
    console.log('Server listening on port 3000');
  };
});
于 2013-07-20T15:14:51.457 回答