NodeJs(三)——get/post请求及路由
-
获取get请求内容
由于get请求直接被嵌入在路径中,URL是完整的请求路径,包括了?后面的部分,因此你可以手动解析后面的内容作为get请求的参数。
node.js 中 url 模块中的 parse 函数提供了这个功能。- url.parse(urlString[,parseQueryString[,slashesDenoteHost]])
- urlString:url字符串
- parseQueryString
- true:表示把请求参数query属性解析为对象
- false:字符串
- slashesDenoteHost
- true:表示如果地址中没有明确写出协议时,也能正确解析
案例
- 新建文件:
getServer.js
,代码如下所示:
var http = require('http'); var url = require('url'); var util = require('util'); http.createServer(function(req, res){ res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'}); res.end(util.inspect(url.parse(req.url, true))); //util.inspect()是一个将任意对象转换为字符串的方法,通常用于调试和错误输出。 }).listen(8888,()=>{ console.log(`Server running at localhost:8888`); });
- 在浏览器中访问
http://localhost:8888/user?name=get请求方式&url=www.rundo.com
然后查看返回结果:
- url.parse(urlString[,parseQueryString[,slashesDenoteHost]])
-
获取 URL 的参数
- 在以上基础上加入下面的代码:
// 解析 url 参数 var params = url.parse(req.url, true).query; res.write("请求名:" + params.name+"\n"); res.write("请求URL:" + params.url); res.end();
- 在浏览器中访问
http://localhost:8888/user?name=get请求方式&url=www.rundo.com
然后查看返回结果:
- 在以上基础上加入下面的代码:
-
获取post请求内容
POST 请求的内容全部的都在请求体中,http.ServerRequest 并没有一个属性内容为请求体,原因是等待请求体传输可能是一件耗时的工作。
-
当请求这个页面时,如果post数据中没有name和url,则返回一个提交页面;如果有name和url,则打印。
-
post请求会触发"data"事件。
-
chuck使用+=保存,因为会额外请求favicon.ico,导致body={}。
-
请求结束,会触发"end"事件。将chuck反序列化querystring.parse(body)为对象数组, 使用body.name访问post变量。
- 新建js文件postServer.js
var http = require('http'); var querystring = require('querystring'); var postHTML = // 定义了一个post变量,用于暂存请求体的信息 '<html><head><meta charset="utf-8"><title>post请求实例</title></head>' + '<body>' + '<form method="post">' + '请求名: <input name="name"><br>' + '请求URL: <input name="url"><br>' + '<input type="submit">' + '</form>' + '</body></html>'; http.createServer(function (req, res) { var body = ""; req.on('data', function (chunk) { // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中 body += chunk; //一定要使用+=,如果body=chunk,因为请求favicon.ico,body会等于{} }); req.on('end', function () { // 在end事件触发后,通过querystring.parse将post解析为真正的POST请求格式,然后向客户端返回 // 解析参数 body = querystring.parse(body); // 设置响应头部信息及编码 res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'}); if(body.name && body.url) { // 输出提交的数据 res.write("网站名:" + body.name); res.write("<br>"); res.write("网站 URL:" + body.url); } else { // 输出表单 res.write(postHTML); } res.end(); }); }).listen(8888,()=>{ console.log(`Server running at localhost:8888`); }); ```
- 终端执行:
node postServer
- 浏览器访问:
localhost:8888
✌️✌️✌️
-
✌️✌️✌️
mkdir route
touch route.js
cd route
mkdir html
cd html
touch product.html
touch details.html
-
touch my.html
✌️✌️✌️
-
route.js
// 加载所需模块 var http = require('http'); var url = require('url'); var fs = require('fs'); var hostname = '127.0.0.1'; var port = 8888; http.createServer((req,res)=>{ //箭头函数 var pathname = url.parse(req.url).pathname; //找出浏览器请求的 URL 路径 if(req.url!=='/favicon.ico'){ // 去掉/favicon.ico 请求 console.log(pathname); console.log('Request for ' + pathname + ' received.'); function showPaper(path,status){ var content = fs.readFileSync(path); res.writeHead(status, { 'Content-Type': 'text/html;charset=utf-8' }); res.write(content); res.end(); } switch(pathname){ case '/': case '/product': //'商品列表页' showPaper('./html/product.html',200); break; case '/details': //'商品详情页' showPaper('./html/details.html',200); break; default: showPaper('./html/my.html',200); //'我的页' break; } } }).listen(port,hostname,()=>{ //监听 console.log(`Server running at http://${hostname}:${port}/`); });
-
product.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>商品列表页</title> <style> h1{ color: skyblue; } </style> </head> <body> <h1>这是商品列表页</h1> </body> </html>
-
details.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>商品详情页</title> <style> h1{ color: red; } </style> </head> <body> <h1>这是商品详情页</h1> </body> </html>
-
my.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>我的页</title> <style> h1{ color: pink; } </style> </head> <body> <h1>我的页面</h1> </body> </html>
- 终端输入:
node route
- 浏览器访问:
-
localhost:8888
或localhsot:8888/product
localhsot:8888/details
-
localhsot:8888/my
✌️✌️✌️✌️✌️✌️
-
- 终端输入: