# 3.cookie、长连接、数据协商

1.cookie的属性

  • max-ageexpires设置过期时间
  • Secure只在https的时候发送
  • HttpOnly无法通过document.cookie访问
http.createServer((request,response)=>{
  const host = request.headers.host
  if (request.url==='/') {
    if (host==='a.test.com:9000') {
      fs.readFile('./test.html','utf8',(err,content)=>{
        response.writeHead(200, {
          'Content-Type':'text/html',
          'Set-Cookie':['id=123; max-age=200','abc=456;max-age=2;domain=test.com;HttpOnly']
        })
        response.end(content)
      })
    }else {
      response.end('123')
    }
  }
}).listen(httpPort,()=>{ console.log('Server lintening on http://localhost:%s',httpPort) })

2.长连接 一个tcp可以发送多个http请求

http.createServer((request,response)=>{
  // const html = fs.readFileSync('./test.html','utf8')
  const html = fs.readFileSync('./test.html') //gzip
  const img = fs.readFileSync('./timg.jpg')
  if (request.url==='/') {
    response.writeHead(200, {
      'Content-Type':'text/html',
      // 'Content-Encoding':'gzip',
      'Connection':'close' // 长连接设置
    })
    response.end(html)
    // response.end(zlib.gzipSync(html))
  }else {
    response.writeHead(200, {
      'Content-Type':'image/jpg',
      // 'Content-Type':'text/html',
    })
    response.end(img)
  }
}).listen(httpPort,()=>{ console.log('Server lintening on http://localhost:%s',httpPort) })

3.数据协商/压缩

浏览器:Accept Accept-Encoding Accept-Language User-Agent

服务器:Content-Type

4.form 的enctype对应request header中的Content-type,它有三个可以选值

  • application/x-www-form-urlencodedmultipart/form-datatext/plain
  • 其中包含file的时候要选multipart/form-data