Node.js——请求头部报文

请求头部报文

  1. general 请求基本信息
  2. response Headers -->响应头
  3. request headers --> 请求头
  4. 携带参数
    • query string paramters get请求
    • form data post请求

代码例子

const http = require( 'http' );//引入内置模块http
const HOST = 'localhost';//设置域名
const PORT = 8000; //设置端口号


http.createServer(( request,response ) => {//创建服务器

  // response.writeHead( 状态码,请求头 )
  response.writeHead( 200, {
    'Content-type': 'text/html;charset=utf8'
  })

    const http = require( 'http' )
   
    const cheerio = require( 'cheerio' ) // 引入第三方类库

    const options = {
      hostname: '',//域名
      port: 80,
      path: '/url',
      method: 'GET',
      headers: {
       /*
      网页请求头内容
       */
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': 0
      }
    }


    http.get( options, (res) => {


      const { statusCode } = res; // 获取请求状态码  200 301 302 303 304 404  500 
      const contentType = res.headers['content-type']; // 获取请求类型数据类型

      // json数据的content-type         'content-type': 'application/json'


      res.setEncoding('utf8'); // 字符编码
      let rawData = '';
      res.on('data', (chunk) => { rawData += chunk; }); // 通过data事件拼接数据流
      res.on('end', () => { // 获取数据结束了 
        try { // 高级编程语法       
          // console.log( rawData )
          const $ = cheerio.load( rawData );
          $('div a').each(function (index,item) {//选取包含要发往前端信息的元素并且遍历其内容
          
            response.write(`<h3> ${ $( this ).text() }  </h3>`) // 往前端发送信息
          });
          response.end(); // 告诉前端信息发送已经结束了
        } catch (e) {//  捕获错误信息
          console.error(e.message);
        }
      });
    }).on('error', (e) => {
      console.error(`Got error: ${e.message}`);
    });

  
  
}).listen( PORT,HOST,() => {//事件监听
  console.log( `The server is running at: http://${ HOST }:${ PORT }` );
})
发布了12 篇原创文章 · 获赞 1 · 访问量 6040

猜你喜欢

转载自blog.csdn.net/shuureina/article/details/96505920