zl程序教程

您现在的位置是:首页 >  后端

当前栏目

NodeJs——(8)http.ServerRequest的过程

NodejsHTTP 过程
2023-09-14 09:04:42 时间
①http.ServerRequest提供了3个事件用于控制请求体传输: 【1】data:当请求体数据到来时,该事件被触发,提供一个参数给回调函数,是接受到的数据,该事件可能被多次调用(所有data按顺序的集合,是请求体数据)。如果该事件没有被监听,请求体将被抛弃; 【2】end:当请求体数据完成时该事件触发。此后不再触发da

(25)http.ServerRequest的过程

①http.ServerRequest提供了3个事件用于控制请求体传输:

【1】data:当请求体数据到来时,该事件被触发,提供一个参数给回调函数,是接受到的数据,该事件可能被多次调用(所有data按顺序的集合,是请求体数据)。如果该事件没有被监听,请求体将被抛弃;

 

【2】end:当请求体数据完成时该事件触发。此后不再触发data事件;

 

【3】close:用户当前请求结束时,该事件被触发。不同于end,如果用户强制终止了传输,也还是调用close

 

 

②获取GET请求内容

【1】GET请求被直接内嵌在路径中。URL是完整的请求路径(包括?后面的部分),因此手动解析后面的内容作为GET请求的参数。

 

Node.js的url模块中的parse函数提供了这个功能。

以url:http://127.0.0.1/user?name=byvoid email=byvoid@byvoid.com为例:

先上代码:

var http = require("http");

var url = require("url");

var server = new http.Server();

server.on("request", function (req, res) {

 if (req.url == "/favicon.ico") {

 return;

 var m = url.parse(req.url, true);

 console.log(m)

 res.writeHead(200, {Content-type: text/html;charset = utf8});

 res.end();

server.listen(80);

console.log("The server begin");


通过console.log返回的内容是:

Url {

  protocol: null,

  slashes: null,

  auth: null,

  host: null,

  port: null,

  hostname: null,

  hash: null,

  search:?name=byvoid email=byvoid@byvoid.com,

  query: { name: byvoid, email:byvoid@byvoid.com },

  pathname: /user,

  path:/user?name=byvoid email=byvoid@byvoid.com,

  href:/user?name=byvoid email=byvoid@byvoid.com }


其中几个关键是:

pathname是我们关心的url地址请求;而path是完整的部分

query是get方法的部分;在这里包含了name和email两个属性,他们中间用 相连接;

 

于是,想要获取GET请求的方法,只需要通过url的query部分即可;

 

 

③获取POST请求内容:

POST方法的请求内容,被放置在请求体之中,即之前的data、end、close相关事件;

 

post方法的请求体内容的解析方法是利用querystring模块的parse方法;

var http = require("http");

var querystring = require("querystring");

var server = new http.Server();

server.on("request", function (req, res) {

 if (req.url == "/favicon.ico") {

 return;

 if (req.url !== "/post") { //默认页面是这个

 var body =  html  +

  head  +

  meta http-equiv="Content-Type" content="text/html;  +

 charset=UTF-8" /  +

  /head  +

  body  +

  form action="/post" method="post"  +

  textarea name="text" rows="20" cols="60" /textarea  +

  input type="submit" value="Submit text" /  +

  /form  +

  /body  +

  /html 

 res.writeHead(200, {Content-type: text/html;charset = utf8});

 res.write(body);

 res.end();

 } else { //当提交表单后,跳转到这个页面

 var PostData = null; //这个变量用于存储全部数据

 req.on("data", function (data) { //因为可能多次data事件,因此需要通过+=来完成

 PostData += data;

 req.on("end", function () { //当data事件触发完毕后会触发这个事件,返回事件必须写在这里,不然PostData是空

 var message = querystring.parse(PostData); //进行解析,变成一个对象

 console.log(message); //显示这个对象

 res.writeHead(200, {Content-type: text/html;charset = utf8}); //返回

 if (PostData)

 res.write(message.nulltext);

 res.end();

server.listen(80);

console.log("The server begin");



 

PS:按照说明,这种方法有严重效率问题和安全隐患。因此不能在真正的生产环境中使用这种方法。

个人推测,实际使用中一般使用的都是模板,比如ejs或者jade