Nodejs之http的表单提交

发布时间:2025-04-17 点击:5
post方法提交表单数据
向服务器提交数据需要使用post方法,get方法的请求信息都在查询字符串中,没有请求体,而post方法的传输的数据都在请求体中,故提交表单数据时需要使用post方法。
req是请求信息,req.url表示请求的地址,当服务器运行之后,req请求的网址为127.0.0.1:3000,此时req.url为‘/',则返回的是一串表单数据,在表单数据中设置了method是post,action是‘/url',表面提交数据的方式是post,将数据提交的地址为127.0.0.1:3000/url,而提交之后要获取新的页面即127.0.0.1:3000/url,此时req.url为‘/url',故显示的另一个页面。
<script>
//提交表单数据
var http=require('http');
var querystring=require('querystring');
var server=http.createserver(function (req,res) {
//req.url不同则返回的页面不同
if('/'==req.url){
res.writehead(200,{'content-type':'text/html'});
res.write([
'<form method=post action=/url>',
'<h1>my form</h1>',
'<fieldset>',
'<label>personal information</label>',
'<p>what is your name?</p>',
'<input type=text name=name>',
'<button>submit</button>',
'</form>'
].join(''));
res.end();
}else if('/url'==req.url&&req.method=='post'){
var reqbody='';
req.on('data',function (data) {
reqbody += data;
});
req.on('end',function () {//用于数据接收完成后再获取
res.writehead(200,{'content-type':'text/html'});
res.write('you have sent a '+req.method+' request\n');
res.write('<p>content-type:'+req.headers['content-type']+'</p>'
+'<p>data:your name is '+querystring.parse(reqbody).name+'</p>');
res.end();
})
}else{
res.writehead(404);
res.write('not found');
res.end();
}
}).listen(3000,function () {
console.log('server is listening 3000');
});
</script/>
提交之后,需要获取请求信息的请求体,因为post方法中信息都在请求体中,用req绑定data事件获取数据,这里需要注意的是必须得在数据接收完成后再对数据进行操作,即必须绑定end事件监听请求信息是否传输完成。
querystring是查询字符串模块,用于对查询字符串的解析,parse方法将查询字符串解析成一个对象。
运行结果:
提交数据后:


B2C商城建设流程,电商网站建设流程
网站建设怎么做能让用户对网站产生信任感
【SEO必知的100个网站优化问答】带来的投票
怎么样找到好的友情链接
网站建设为什么还要去备案呢
小企业网站的排名如何超过大型公司?企业网站优化怎么做?
文章分页在网站建设中可以提高浏览量
营销型网站建设的作用是什么