文章目录
- 使用http.createServer([requestListener]) 创建HTTP服务器
- http服务器的显式实现方法
- http.ServerRequest 获取get请求内容
- http.ServerRequest 获取post请求内容
使用http.createServer([requestListener]) 创建HTTP服务器
const http = require('http'); // 创建http.Server 的实例 // 第一个参数是请求体参数,第二个参数是响应体参数 http.createServer((req,res)=>{ console.log("请求体\r\n",req,"\r\n"); res.writeHead(200,{'Content-Type':'text/html'}); res.write(`<h1>node.js</h1>`); res.end(); }).listen(8080,'127.0.0.1'); //listen设置的是浏览器访问的ip跟端口 console.log("HTTP server is running \r\n => at 127.0.0.1:8080");
http服务器的显式实现方法
const http = require('http'); const server = new http.Server(); server.on('request',(req,res)=>{ res.writeHead(200,{'Content-Type':"text/html"}); res.write(`<h1>httpServer</h1>`); res.end(`<p>hello js</p>`); }) server.listen(3000,'127.0.0.2'); console.log("Http server is listening at => 127.0.0.2:3000");
http.ServerRequest 获取get请求内容
const http = require('http'); const url = require('url'); const util = require('util'); http.createServer((req,res)=>{ res.writeHead(200,{'Content-Type':'text/plain'}); res.end(util.inspect(url.parse(req.url,true))); }).listen(3000,'127.0.0.1'); console.log("Server is listening at : \r\n => 127.0.0.1:3000");
http.ServerRequest 获取post请求内容
const http = require('http'); const querystring = require('querystring'); const util = require('util'); http.createServer((req,res)=>{ var post = ''; req.on('data',chunk=>{ post += chunk; }); req.on('end',function(){ post = querystring.parse(post); res.end(util.inspect(post)); }) }).listen(8080); console.log("Server is listening at 127.0.0.1:8080");
- 初学,不是很理解, 后面再回来注释