美文网首页Vue技术
nodejs http模块

nodejs http模块

作者: RickyWu585 | 来源:发表于2022-02-08 14:28 被阅读0次
    • 创建一个模块
    const server = http.createServer()
    
    • 监听请求
    server.on('request',(request,response) => {
      console.log('有人请求了');
      response.end('hi')  //响应的内容
    })
    
    • 启动http服务器监听连接
    server.listen(8888)
    
    • 设置响应内容
    response.end('hi')
    
    • 获取请求体:监听requestdata事件,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());
    });
    
    

    相关文章

      网友评论

        本文标题:nodejs http模块

        本文链接:https://www.haomeiwen.com/subject/dqswkrtx.html