💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 前言 对于vue项目中的xhr的请求统一建议使用相关的模块工具,这里推荐给大家两个,axios以及whatgw-fetch. 这两个工具是同一作者,支持xhr的html,json,表单,文件等多种类型的请求,功能比较强大。 ## 安装 * npm以及bower安装 ~~~ npm install whatwg-fetch --save; or bower install fetch. ~~~ * webpack以及js中的使用 `entry: ['whatwg-fetch', ...]` * es2015中的使用 `import 'whatwg-fetch'` ## 使用 * html使用 ~~~ fetch('/users.html') .then(function(response) { return response.text() }).then(function(body) { document.body.innerHTML = body }) ~~~ * json使用 ~~~ fetch('/users.json').then(function(response) { console.log(response.headers.get('Content-Type')) console.log(response.headers.get('Date')) console.log(response.status) console.log(response.statusText) }) ~~~ * form的使用,可以直接提交表单数据 而不用分别封装 ~~~ var form = document.querySelector('form') fetch('/users', { method: 'POST', body: new FormData(form) }) ~~~ * post json的使用 ~~~ fetch('/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Hubot', login: 'hubot', }) }) ~~~ * File upload ~~~ var input = document.querySelector('input[type="file"]') var data = new FormData() data.append('file', input.files[0]) data.append('user', 'hubot') fetch('/avatars', { method: 'POST', body: data }) ~~~ ## 检测网络状态 * 针对xhr特殊的状态码 ,可以抛出异常 进行统一的异常处理 ~~~ //检查返回状态码 function checkStatus(response) { if (response.status >= 200 && response.status < 300) { return response } else { var error = new Error(response.statusText) error.response = response throw error } } //转换为标准的json类型 function parseJSON(response) { return response.json() } //某条具体的指令 或者匹配型的指令 统一处理 fetch('/users') .then(checkStatus) .then(parseJSON) .then(function(data) { console.log('request succeeded with JSON response', data) }).catch(function(error) { console.log('request failed', error) }) ~~~ ## CORS * 发送cookie,当前的域名如果要直接发送cookie,需要设置credentials The "same-origin" value makes fetch behave similarly to XMLHttpRequest with regards to cookies. Otherwise, cookies won't get sent, resulting in these requests not preserving the authentication session. ~~~ fetch('/users', { credentials: 'same-origin' }) ~~~ * For CORS requests, use the "include" value to allow sending credentials to other domains: ~~~ fetch('https://example.com:1234/users', { credentials: 'include' }) ~~~ ## Browser Support Chrome Firefox Safari 6.1+ Internet Explorer 10+ ## 参考资料 * [whatwg-fetch模块介绍](https://npm.taobao.org/package/whatwg-fetch)