一、 数据协商
分类:
客户端请求:
Accept:
Accept:表明 我想要什么样的数据
Accept-Encoding:数据是什么样的编码方式 进行传输。主要限制 服务端怎样进行数据的压缩。
Accept-Language:根据这个 判断 返回的数据是什么语言。
User-Agent:标识浏览器相关的信息。
服务器返回内容:
Content
Content-Type:选择一种返回的数据格式 进行数据返回。
Content-Encoding:服务端 用了什么样的 压缩方式。
Content-Language:判断通过请求返回的什么语言。
server.js 代码
const http = require(‘http‘)const fs = require(‘fs‘)const zlib = require(‘zlib‘)http.createServer(function (request, response) { ?console.log(‘request come‘, request.url) ?const html = fs.readFileSync(‘test.html‘) ?response.writeHead(200, { ???‘Content-Type‘: ‘text/html‘, ???// ‘X-Content-Options‘: ‘nosniff‘ //告诉浏览器不要随意猜测我返回的数据类型 ???‘Content-Encoding‘: ‘gzip‘ //压缩方式 ?}) ?response.end(zlib.gzipSync(html))}).listen(8888)console.log(‘server listening on 8888‘)
test.html 代码
<!DOCTYPE html><html lang="en"><head> ?<meta charset="UTF-8"> ?<meta name="viewport" content="width=device-width, initial-scale=1.0"> ?<meta http-equiv="X-UA-Compatible" content="ie=edge"> ?<title>Document</title></head><body> ?<form action="/form" id="form" enctype="application/x-www-form-urlencoded"> ???<input type="text" name="name"> ???<input type="password" name="password"> ???<input type="file" name="file"> ???<input type="submit"> ?</form> ?<script> ???var form = document.getElementById(‘form‘) ???form.addEventListener(‘submit‘, function (e) { ?????e.preventDefault() ?????var formData = new FormData(form) ?????fetch(‘/form‘, { ???????method: ‘POST‘, ???????body: formData ?????}) ???}) ?</script></body></html>
请求返回结果:压缩前后
post 数据返回格式:
二、 Redirect
const http = require(‘http‘)http.createServer(function (request, response) { ?console.log(‘request come‘, request.url) ?if (request.url === ‘/‘) { ???response.writeHead(302, { ?// or 301 慎用 直接访问 /new 302要先经过服务端的一次跳转 才能访问 /new ?????‘Location‘: ‘/new‘ ???}) ???response.end() ?} ?if (request.url === ‘/new‘) { ???response.writeHead(200, { ?????‘Content-Type‘: ‘text/html‘, ???}) ???response.end(‘<div>this is content</div>‘) ?}}).listen(8888)console.log(‘server listening on 8888‘)
访问结果:
HTTP 各种特性应用(三)
原文地址:https://www.cnblogs.com/zhangtaotqy/p/9416247.html