• [JS] 网络请求相关


    本文介绍如下内容:

    1. XMLHttpRequest
    2. Fetch
    3. WebSocket

    三个浏览器原生支持的发送网络请求的方法。

    XMLHttpRequest

    1. 创建 xhr 对象:const xhr = new XMLHttpRequest()
    2. 调用 open 方法准备发送请求:xhr.open(method, url, async, username, password)
    3. 使用 setRequestHeader 添加请求头:xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
    4. 调用 send 方法发送实际请求:xhr.send(null)xhr.send(str) 表示 POST 的 body

    xhr.open 的第三个参数为一个 bool 值,表示是否异步发送请求,为 true 则需要在 xhr.onreadystatechange 事件监听方法上添加一个监听方法。当 xhr.readyState === 4 时表示请求发送成功并获取到响应。一般使用异步请求方式。

    const xhr = new XMLHttpRequest()
    
    xhr.onreadystatechange = function() {
    	if(xhr.readyState === 4) {
    		const status = xhr.status
    		if(status >= 200 && status < 300 || status === 304) {
    			const data = JSON.parse(xhr.responseText)
    		} else {
    			alert('request failed:', status)
    		}
    	}
    }
    
    xhr.open('get', '/', true)
    xhr.send(null)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    FormData

    FormData 是 XMLHttpRequest Level 2 的内容,主要是为了简化表单序列化的操作。

    const form = new FormData(document.forms[0])
    form.append('a', 'b')
    form.has('a') // true
    form.get('a') // b
    form.getAll('a') // ['b']
    form.delete('c')
    form.entries()
    
    // 直接传入 FormData 对象,会自动根据表单的 enctype 设置请求头
    xhr.send(form)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    可以看到 FormData 的操作基本类似 Map

    fetch

    fetch 返回一个 Promise,用于现代浏览器的网络请求。

    fetch('/').then(response => response.json()).then(json => {
    	console.log(json)
    })
    
    • 1
    • 2
    • 3

    fetch 的 init 参数

    默认情况下 fetch 只发送 GET 请求,可以通过 fetch 的第二个参数改变 fetch 的行为。init 对象的键值有:

    • body 请求的请求体,必须是 Blob、BufferSource、FormDataURLSearchParams、ReadableStream 或 String 的实例
    • cache
    • credentials 携带 cookie 的策略,取值为:
      • omit 不发送 cookie
      • same-site 同源携带
      • include 无论同源还是跨源都包含 cookie
      • 默认为 same-site
    • headers 请求头
    • method 请求方法,默认为 GET
    • mode 跨域的模式,取值为:
      • cors 遵循浏览器的 CORS 策略
      • no-cors 仅简单请求支持 CORS
      • same-origin 不允许跨域
    • redirect 重定向相关
    • referrer HTTP referer 头相关

    fetch 的常用请求模式

    携带 json

    fetch('/send-json', {
    	method: 'POST',
    	// 必须指定 content-type
    	headers: {
    		'content-type': 'application/json'
    	},
    	body: JSON.stringfy({age: 1, name: 12})
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    携带表单参数

    fetch('/send-form', {
    	method: 'POST',
    	// 必须指定 content-type
    	headers: {
    		'content-type': 'application/x-www-form-urlencoded'
    	},
    	// encoded 表单传参格式
    	body: 'a=1&b=2'
    })
    
    const form = new FormData()
    form.append('name', 111)
    form.append('age', 1232)
    
    fetch('/send-form', {
    	method: 'POST',
    	// encoded 表单传参格式
    	body: form
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    发送文件

    let imageFormData = new FormData();
    let imageInput = document.querySelector("input[type='file']");
    imageFormData.append('image', imageInput.files[0]);
    fetch('/img-upload', {
     method: 'POST',
     body: imageFormData
    });
    
    // 这个 fetch()实现可以支持多个文件:
    let imageFormData = new FormData();
    let imageInput = document.querySelector("input[type='file'][multiple]");
    for (let i = 0; i < imageInput.files.length; ++i) {
     imageFormData.append('image', imageInput.files[i]);
    }
    fetch('/img-upload', {
     method: 'POST',
     body: imageFormData
    });  
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    WebSocket

    // websocket 的 URL 必须为绝对路径,同时不受 CORS 策略影响,但是服务器可以判断请求来源
    const socket = new WebSocket("ws://www.example.com/server.php"); 
    // 发送数据
    socket.send('hello world')
    
    // 接受数据
    socket.onmessage = function(event) {
     let data = event.data;
     // 对数据执行某些操作
    }; 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    更多内容见 MDN。

  • 相关阅读:
    Windows AD域报表
    grafana的前端二次开发初体验
    【电路笔记】-平均电压和均方根电压(RMS Voltage)
    JDK9-17新特性
    最小生成树模板prim和kruskal
    VulnHub--Lampiao-linux脏牛漏洞提权
    基于机器人自主移动实现SLAM建图
    故障预测与健康管理(PHM)在工业领域的发展前景
    图像仿射变换与双线性插值
    【趣味实践】Stable Diffusion绘制中秋美景
  • 原文地址:https://blog.csdn.net/qq_39559879/article/details/126945822