zoukankan      html  css  js  c++  java
  • 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.js

    const BASE_API = process.env.BASE_API export const http = (type, url, data) => { url = BASE_API + url let 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()

    浏览器支持:

  • 相关阅读:
    CF949C Data Center Maintenance 题解
    P1438 无聊的数列 题解
    CF620E New Year Tree 题解
    结构体优先队列的定义
    CF464E The Classic Problem 题解
    CF427C Checkposts
    CF161D Distance in Tree 题解
    P4375 [USACO18OPEN]Out of Sorts G 题解
    SCI, SCIE, 和ESCI的区别
    Matlab画图中图的方法
  • 原文地址:https://www.cnblogs.com/dora-zc/p/10067383.html
Copyright © 2011-2022 走看看