當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
fetch + async await 使用原生JS发送网络请求
生活随笔
收集整理的這篇文章主要介紹了
fetch + async await 使用原生JS发送网络请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
由于現在主流瀏覽器支持Fetch API,無需引用其他庫就能實現AJAX,一行代碼就搞定,可以說是非常方便了。
1 export default { 2 name: 'HelloWorld', 3 data() { 4 return { 5 items: [] 6 } 7 }, 8 mounted() { 9 this.getData() 10 }, 11 methods: { 12 async getData() { 13 this.items = await (await fetch('http://localhost:8081/list')).json() 14 } 15 } 16 }?封裝使用:
... mounted() {api.getData().then(res => {this.items = res}).catch(err => {console.log(err)}) }, ... // src/api/index.jsconst BASE_API = process.env.BASE_APIexport const http = (type, url, data) => {url = BASE_API + urllet options = {}if (type === 'post') {options = {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ data: data })}} else if (type === 'get') {if (data && typeof data === 'object') {const paramArray = []Object.keys(data).forEach(key => paramArray.push(key + '=' + data[key]))if (url.indexOf('?') === -1) {url += '?' + paramArray.join('&')} else {url = '&' + paramArray.json('&')}options = { method: 'GET' }} else if (!data) {options = { method: 'GET' }} else {alert('參數有誤')}}return fetch(url, options) }export const getData = async(data) => await (await http('get', '/list', data)).json()
?
瀏覽器支持:
?
轉載于:https://www.cnblogs.com/dora-zc/p/10067383.html
總結
以上是生活随笔為你收集整理的fetch + async await 使用原生JS发送网络请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Springboot实现文件下载功能
- 下一篇: js中的各种宽度计算