const server = http.createServer()
server.on('request',(request,response) => {
console.log('有人请求了');
response.end('hi') //响应的内容
})
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'); //响应的内容
});
});
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());
});
网友评论