使用 nodejs http 模块 搭建小型web服务器
2020年7月19日request 请求头 常用属性和方法
1 2 3 |
request.headers //获取请求报文 request.url //获取请求地址 url request.method //获取请求方法 GET POST |
response 响应头 常用属性和方法
http状态码
- 200 请求成功
- 400 客户端请求有语法错误
- 404请求的资源没有被找到
- 500 服务器内部错误
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * 200 :为请求响应状态码 * content-type :为文件类型 charset 指定文件编码 */ res.writeHead(200,{ 'content-type': 'text/html;charset=utf8' }) /** * 写好响应头就可以知己返回文件了 */ response.end(数据) |
URL模块 常用方法
1 2 |
url.parse('https://www.zfajax.com/wp-admin/post.php?post=2192&action=edit') //解析url 获取url的详细数据 url.parse('https://www.zfajax.com/wp-admin/post.php?post=2192&action=edit', true) //解析url 获取url的详细数据 将query对象化 |
querystring模块 常用方法
1 2 |
//name=123&age=123 这个就是query参数实例 querystring.parse(postParams) //解析query参数 ,返回一个对象 |
获取post的请求参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
const http = require('http') const app = http.createServer(); app.on('request', (request, response) => { let postParams = ''; /** * post:参数是通过事件的方式来接收的 * 当参数产传递的时候发出 data 事件 * 这里只可以是post */ request.on('data', (params) => { /** * 因为数据是分段,来的所以数据要+= */ postParams += params }) /** * 当参数传递完成的时候发出 end 事件 * 这里的参数传递结束,可以是get 或 post */ request.on('end', () => { console.log(querystring.parse(postParams)) }) response.end('ok') }) app.listen(3000) console.log('网站服务器启动成功') |
小型web服务器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
const http = require('http') //引入http模块 const url = require('url') //引入url模块 专门处理url参数的 const path = require('path') //引入path路径模块 const fs = require('fs') //引入文件读取模块 const mime = require('mime') //引入mime用于获取文件类型 const app = http.createServer(); /** * 给app绑定 request 请求事件, * request : 请求对象 * response : 相应对象 */ app.on('request', (request, response) => { let method = request.method.toLowerCase(); //获取请求方式 let {query, pathname} = url.parse(request.url, true) //解析url中的 path 问毫之前端口号之后的数据 let readPath = path.join(__dirname, pathname) //将项目路径和请求路径结合就是 html所在的文件路径 if (method == 'get') { //判断请求类型 fs.readFile(readPath, (error, result) => { //获取文件 if (error != null) { //如果不是文件 response.writeHead(200, { 'content-type': 'text/html;charset=utf-8' }) /** * 这里就是路由层根据不同的 * pathname返回不同的参数 */ if (pathname == '/' || pathname == '/index') { response.end('欢迎来到首页') }else if (pathname == '/list') { response.end('欢迎来到列表页') }else { response.end('您访问的页面不存在') } } else { response.writeHead(200, { 'content-type': `${mime.getType(readPath)}` }) response.end(result) } }) } else if (method == 'post') { } }) app.listen(3000); //监听端口 console.log('http服务器启动成功') |