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()

    浏览器支持:

  • 相关阅读:
    近来感受
    GIT相关命令
    CMMI评审总结
    Windows下Git Bash的设置
    PHP学习三--常用运算符和结构语句
    PHP学习二--常量
    MYSQL基础十一--存储引擎
    MYSQL基础十--存储过程
    MYSQL基础九--自定义函数
    MYSQL基础八--子查询和连接
  • 原文地址:https://www.cnblogs.com/dora-zc/p/10067383.html
Copyright © 2011-2022 走看看