const fs = require('fs')
const http = require('http')
const zlib = require('zlib') // 压缩
const createReadStream = fs.createReadStream('./test.html') // 读取文件流
// 充当客户端向远程地址发起请求
http.get('http://nodejs.cn/api/http.html', (res)=>{
console.log(res.statusCode);
let rawData = ''
res.on('data', (chunk)=> { // 获取服务端响应的数据
rawData += chunk
})
res.on('end', ()=> {
console.log(rawData.toString());
})
})
// 充当服务器
const app = http.createServer()
app.on('request', (req,res)=> {
console.log(req.url);
console.log(req.method);
console.log(req.headers);
/*响应头,200*/
res.writeHead(200,{
'Content-Type' : 'text/html;application/json;charset=utf-8'
})
res.write('')
res.end()
/*响应头,302*/
res.writeHead(302,{
Location: 'http://www.baidu.com'
})
res.end()
/*响应头,404*/
res.writeHead(404)
res.write('404')
res.end()
/*响应体内容:普通文本*/
res.write('<h1>nodejs中文</h1>')
res.end()
/*响应体内容:文件*/
let file = fs.readFileSync('./test.html')
res.write(file)
res.end()
/*使用gzip压缩*/
res.writeHead(200,{
'Content-Type' : 'text/html;application/json;charset=utf-8',
'Content-Encoding': 'gzip'
})
const gzip = zlib.createGzip()
createReadStream.pipe(gzip).pipe(res) // 通过管道压缩后进行响应发送
})
app.listen(8080)
HttpServer使用
最新推荐文章于 2026-06-17 14:30:32 发布
这段代码展示了Node.js中如何使用http模块发起GET请求,处理响应数据,以及创建服务器并处理不同类型的响应。同时,它还涉及到了文件流的读取和zlib库的gzip压缩。通过管道将压缩后的文件流直接发送到响应中。

1698

被折叠的 条评论
为什么被折叠?



