使用fetch跨域获取数据

本文介绍如何在Vue项目中通过fetch.js和request.js工具文件实现跨域获取数据,详细讲解了在home.vue组件中调用接口获取数据的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.先创建工具文件util 以及封装接口的文件
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

fetch.js文件


import { Toast } from 'vant';
//允许同时存在多个 Toast
Toast.allowMultiple();

// let dataurl = 'https://test.365msmk.com/api/app'
let dataurl = '/api'
const Http = function () {
  let DeviceID = localStorage.DeviceID;
  if (!DeviceID) {
    DeviceID = Guid.NewGuid().ToString('D');
    localStorage.DeviceID = DeviceID;
  }
  this.DeviceID = DeviceID;
};

Http.prototype.fetch = function (url, method, params = {}) {
  url = dataurl + url;
  let config = { method: method, mode: 'cors' };//, mode: 'cors'
  //判断是否为wx内置浏览器
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    config.headers = {
      DeviceType: 'WXH5',
      DeviceID: this.DeviceID,
    };
  }
  else {
    config.headers = {
      DeviceType: 'H5',
      DeviceID: this.DeviceID
    };
  }
  //请求loading
    Toast.loading({
      message:"加载中",
      className: 'toast-loading'
    });
  if (params instanceof FormData) {
    config.body = params;
  } else {
    if (method == 'get' || method == 'head') {
      if (url.indexOf('?') > 0) {
        url += '&';
      } else {
        url += '?';
      }
      for (let key in params) {
        url += key + '=' + params[key] + '&';
      }
    } else {
      config.body = JSON.stringify(params);
    }
    config.headers['Content-Type'] = 'application/json'
  }

  if (localStorage.adminToken) {
    config.headers.Authorization = 'Bearer ' + localStorage.adminToken;
  }

  //对fetch的二次封装
  return new Promise((resolve, reject) => {
    fetch(url, config).then(async res => {
      Toast.clear();
      if (res.status == 200) {
        let data = await res.json();
        if (data.code == 200) {
          resolve(data.data || data);
        } else {
          if (data.code == 202) {
            // plugins.checkLogin(false)
          } else if (data.code == 203) {
            resolve(data);
          } else {
            Toast({
              message: data.msg,
              duration: 1000,
              forbidClick: true
            });
          }
        }
      } else {
        reject(res.statusText);
      }
    });
  });
};
//对fetch的方法封装
Http.prototype.get = function (url, params) {
  return this.fetch(url, 'get', params);
};

Http.prototype.post = function (url, params) {
  return this.fetch(url, 'post', params);
};

Http.prototype.put = function (url, params) {
  return this.fetch(url, 'put', params);
};

Http.prototype.delete = function (url, params) {
  return this.fetch(url, 'delete', params);
};

export default new Http();

request.js

import axios from 'axios'
// import { resolve } from 'core-js/fn/promise'

const Request = (params)=>{
    return new Promise((resolve,reject)=>{
        axios({
            ...params
        }).then((res)=>{
            resolve(res)
        }).catch((err)=>{
            reject(err)
        })
    })
}

export default Request

在home.vue中获取数据

<template>
  <div>
    <!-- 轮播 -->
    <Swipe class="my-swipe" :autoplay="3000" >
      <SwipeItem v-for="(item,index) in list" :key="index">
          <img :src="item.banner_img" alt="">
      </SwipeItem>
    </Swipe>
  </div>
</template>
<script>
import { Swipe, SwipeItem } from "vant";
import { banner, cartlist } from "../request/http";
export default {
  components: {
    Swipe,
    SwipeItem
  },
  data() {
    return {
      list: [],
      cartlist: [],
    };
  },
  mounted() {
    this.getBaner();
    cartlist().then((res) => {
      console.log(res);
      this.cartlist = res;
    });
  },
  methods: {
    getBaner() {
      banner().then((res) => {
        console.log(res);
        this.list = res;
      });
    },
  },
};
</script>
<style>
    .my-swipe img{
        width: 100%;
        height:250px ;
    }
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值