重要的http模块
主要用于搭建http服务器和客户端
http中文名,超文本传输协议
-
常用的api
-
创建服务器使用 createServer listen
var http = require('http'); http.createServer(function (req, res) { var urlStr = req.url; // 获取请求的路径 var urlMethod = req.method; // 获取请求的方法 console.log(urlStr); console.log(urlMethod); res.end(); }).listen(8888, function (err) { if (err) { console.error(err); return; } console.log("服务器启动成功"); });
获得get请求参数
var urlObj = url.parse(urlStr,true); console.log(urlObj.query)
-
获得post请求的参数
req.on("data", function (chunk) { console.log(chunk.toString()); });
-
请求处理
var http = require('http'); var url = require('url'); http.createServer(function (req, res) { var urlStr = req.url; var methodStr = req.method; // console.log(req.headers); // 获取请求头 // console.log(req.httpVersion); // 获取http版本 /* * 获取GET请求的参数 // 使用url模块对url进行解析 var urlObj = url.parse(urlStr, true); // 获取get参数 console.log(urlObj.query.name); */ // 获取POST请求的参数 req.on("data", function (chunk) { console.log(chunk.toString()); }); res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"}); res.end(); }).listen(8888, function (err) { console.log("服务器启动成功");
});
* 网页实现请求的发送 ``` var http = require('http'); var url = require('url'); var fs = require('fs'); http.createServer(function (req, res) { var urlStr = req.url; var urlObj = url.parse(urlStr, true); var method = req.method; var pathname = urlObj.pathname; if (pathname == "/login.html") { fs.readFile("login.html", function (err, data) { res.write(data); res.end(); }); } else if (pathname == "/test") { // console.log(urlObj.query); req.on("data", function (chunk) { console.log(chunk.toString()); }); res.end(); } }).listen(8888, "localhost", function (err) { if (err) { console.error(err); return; } console.log("服务器启动成功"); });; ```
-