Node.js 简单表单节点js应用程序
我试图制作一个简单的表单,包含用户名和姓氏,当用户提交信息时,会显示另一个页面。我用html做了一个表单,但我不确定下一步该怎么做?是否有人使用Node.js 简单表单节点js应用程序,node.js,Node.js,我试图制作一个简单的表单,包含用户名和姓氏,当用户提交信息时,会显示另一个页面。我用html做了一个表单,但我不确定下一步该怎么做?是否有人使用node js创建了一个小型的、自包含的表单示例?此示例并不能完全完成您的任务。但它是一个自包含的node.js程序,在收到表单时显示表单和不同的页面 将其复制到文件中,然后运行node filename.js,然后转到http://localhost:3000在浏览器中 注意异步代码结构。我定义了一个处理程序函数,但没有立即执行它。我们将函数传递给ht
node js
创建了一个小型的、自包含的表单示例?此示例并不能完全完成您的任务。但它是一个自包含的node.js程序,在收到表单时显示表单和不同的页面
将其复制到文件中,然后运行node filename.js
,然后转到http://localhost:3000
在浏览器中
注意异步代码结构。我定义了一个处理程序
函数,但没有立即执行它。我们将函数传递给http.createServer,然后调用。listen(3000)
。现在,当HTTP请求传入时,HTTP服务器将向处理程序函数传递req,res
对req
是请求对象(它将包含表单数据;有关如何获取数据的一些提示,请参阅)(我建议您直接加入并构建一个小型Express应用程序。这是一个非常好的框架。)
//app.js
//加载内置的“http”库
var http=require('http');
var util=require('util');
//创建一个函数来处理每个HTTP请求
函数处理程序(req、res){
如果(req.method==“GET”){
log('get');
res.setHeader('Content-Type','text/html');
书面记录(200);
决议结束(“”);
}else if(req.method==“POST”){
console.log('post');
//在这里,您可以使用一个库来提取表单内容
//Express.js web框架可以很好地做到这一点
//为了简单起见,我们将始终在这里以“hello world”作为回应
//var hello=req.body.hello;
var hello='world';
res.setHeader('Content-Type','text/html');
书面记录(200);
res.end(“Hello”+Hello+”!”;
}否则{
书面记录(200);
res.end();
};
};
//创建一个在收到请求时调用“handler”函数的服务器
//并让服务器开始侦听HTTP请求
//回调函数将在将来的某个时间执行,此时服务器
//完成其长期运行任务(设置网络和端口等)
createServer(handler).listen(3000,函数(err){
如果(错误){
log('启动http服务器时出错');
}否则{
log('Server监听端口3000');
};
});
github上有很多示例。例如。
//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');
};
});