Vue技术

nodejs http模块

2022-02-08  本文已影响0人  RickyWu585
const server = http.createServer()
server.on('request',(request,response) => {
  console.log('有人请求了');
  response.end('hi')  //响应的内容
})
server.listen(8888)
response.end('hi')
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');  //设置响应体
  });

实践:实现一个简易静态服务器

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());
});

上一篇下一篇

猜你喜欢

热点阅读