NodeJS的post请求

这一章讲解NodeJS的post请求,post请求是通过请求体获得参数的,下面附上具体的代码.有些知识点和get请求里面的一样,我就不多讲了.如果大家不知道,可以参考上一篇文章.

index.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>NodeJS的post请求</title>
</head>
<body>
<div id="main" style="width:800px;height:400px">
	<div class="group">
		<label for="name">名字</label>
		<input type="text" id="name">
	</div>
	<div class="group">
		<label for="age">年龄</label>
		<input type="text" id="age">
	</div>
	<div class="group">
		<label >性别</label>
		<input type="radio" name="sex" value="男">男
		<input type="radio" name="sex" value="女">女
	</div>
	<div class="group">
		<button id="btn1">post请求</button>
	</div>
</div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
	$("#btn1").on("click",function(){
		//读取表单
		var name=$("#name").val();
		var age=$("#age").val();
		var sex=$("input[name=sex]:checked").val();
		
		//发送请求
		$.post("/addStudent",{
			name:name,
			age:age,
			sex:sex
		},function(data){
			alert(data);
		})
	})

</script>
</html>

index.js

/*
* 这个案例演示POST请求的参数如何获得
* */
var finalhandler=require("finalhandler");
var http=require("http");
var serveStatic=require("serve-static");
var url=require("url");
var fs=require("fs");
var querystring=require("querystring");

//配置静态资源服务器,将public文件夹静态化出来
var serve=serveStatic("public",{"index":["index.html","index.htm"]})

var server=http.createServer(function onRequest(req,res){
	//路由
	var pathname=url.parse(req.url).pathname;
	console.log(pathname);
	if(pathname == "/addStudent"){
		//定义了一个content变量,用于暂存请求体的信息
		var content="";
		
		//通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
		//post请求经常会很长,此时会分段,网上有文章大约是800k左右是一个http报文段
		req.on("data",function(chunk){
			//将段落合并
			content+=chunk;
		});
		
		//当所有数据发送完毕之后,此时会触发end事件
		req.on("end",function(){
			content=querystring.parse(content);
			
			//准备要写入文件的内容
			var data="姓名:"+content.name+"\r\n";
			data+="年龄:"+content.age+"\r\n";
			data+="性别:"+content.sex+"\r\n";
			//写文件
			fs.writeFile('output.txt', data,'utf8', (err) => {
				if (err){
					res.end("error");
				}else{
					res.end("ok");
				}
			});
			//这里一定要写res.end();否则会提示/addStudent is not get
			res.end("chenggong");
		});
	}
	//使用静态资源
	serve(req,res,finalhandler(req,res));
	
})

//listen
server.listen(3000,"127.0.0.1");
console.log("服务器已经运行在3000端口");

猜你喜欢

转载自blog.csdn.net/bhq1711617151/article/details/88296138