nodejs http模块
2022-02-08 本文已影响0人
RickyWu585
- 创建一个模块
const server = http.createServer()
- 监听请求
server.on('request',(request,response) => {
console.log('有人请求了');
response.end('hi') //响应的内容
})
- 启动http服务器监听连接
server.listen(8888)
- 设置响应内容
response.end('hi')
- 获取请求体:监听
request
的data
事件,chunk
是一个buffer
server.on('request', (request: IncomingMessage, response: ServerResponse) => {
console.log('有人请求了');
console.log(request.method);
const array = [];
request.on('data', (chunk) => {
array.push(chunk);
});
request.on('end', () => {
const body = Buffer.concat(array).toString();
console.log('body');
console.log(body);
response.end('hi'); //响应的内容
});
});
- response设置响应信息
request.on('end', () => {
response.statusCode = 400; //状态码
response.setHeader('X-frank','i am frank') //设置响应头
response.end('hi'); //设置响应体
});
- 设置响应体:
write
可以调用多次,end
只能一次就结束了
response.end('hi)
或者response.write('hi')
- 结束请求:
response.end()
实践:实现一个简易静态服务器
import * as http from 'http';
import {IncomingMessage, ServerResponse} from 'http';
import * as fs from 'fs';
import * as path from 'path';
import * as url from 'url';
const server = http.createServer();
const publicDir = path.resolve(__dirname, 'public');
server.on('request', (request: IncomingMessage, response: ServerResponse) => {
const {method, url: requestUrl} = request;
const {host} = request.headers
console.log('requestUrl');
console.log(requestUrl);
const myUrl = new URL(requestUrl,`http://${host}`)
console.log('myUrl');
console.log(myUrl);
const {pathname, search} = myUrl;
console.log('search');
console.log(search);
if (method !== 'GET') {
response.statusCode = 405;
response.end();
return;
}
let fileName = pathname.substr(1);
if (fileName === '') {
fileName = 'index.html';
}
fs.readFile(path.resolve(publicDir, fileName), (err, data) => {
if (err) {
response.statusCode = 404;
response.end();
} else {
//设置缓存
response.setHeader('Cache-Control', 'public,max-age=30000000');
response.end(data.toString());
}
});
});
server.listen(8888, () => {
console.log('hi');
console.log(server.address());
});