4
我试图做一个简单的窗体,用户名和姓氏,当用户提交信息时,显示另一个页面。我在html中做了一个表单,但我不确定接下来要做什么?是否有人使用node js
的小型自包含表单的示例?简单的窗体节点js应用程序
我试图做一个简单的窗体,用户名和姓氏,当用户提交信息时,显示另一个页面。我在html中做了一个表单,但我不确定接下来要做什么?是否有人使用node js
的小型自包含表单的示例?简单的窗体节点js应用程序
这个例子并不完全完成你的任务。但它是一个独立的node.js程序,它在收到表单时显示一个表单和一个不同的页面。
将其复制到文件中,然后运行node filename.js
,然后在浏览器中转到http://localhost:3000
。
注意异步代码结构。我定义了一个handler
函数,但不要立即执行它。我们将功能传递给http.createServer
,然后拨打.listen(3000)
。现在,当HTTP请求进入时,http服务器会将req, res
对传递给处理函数。 req
是请求对象(这将包含表单数据;请参阅this question以获取有关如何获取数据的提示)(我建议您直接进入并构建一个小型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');
};
});
github上有很多例子,例如[看看这个](https://github.com/madhums/node-express-mongoose-demo)。 –