axios实现cros跨域 fetch实现jsonp跨域

axios实现cros跨域

  1. 网站 www.npmjs.com,能搜索到插件安装及使用方式
  2. axios最终返回的是promise对象
  3. axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

从浏览器中创建 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
取消请求
自动转换JSON数据
客户端支持防止 CSRF/XSRF

  1. 测试网址
  • get请求地址: http://vue.studyit.io/api/getlunbo
  • post请求地址:http://vue.studyit.io/api/post
  • jsonp请求地址:http://vue.studyit.io/api/jsonp

使用

1. 安装

cnpm install axios --save-dev

2. 引入

  • 原型链方法-全局使用
import axios from 'axios'

Vue.prototype.axios=axios

输出

  mounted() {
    console.log(this.axios);
  }

输出结果为:axios的底层源码

ƒ wrap() {
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }
    return fn.apply(thisArg, args);
  }
  • 在组件中局部使用
    引入
import axios from 'axios'

输出

  mounted() {
    console.log(axios);
  }

输出结果与原型链引入相同

2. get方式传值

  • 给定src,参数在路径上(例如本例的id和name),问号传值
  mounted() {
    let src="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    axios .get(src).then(res => {
        console.log(res);
      }) .catch((err = {}));
  }
  • 参数不在路径上,get方法传两个参数,第二个参数传值
  mounted() {
    let src="http://www.phonegap100.com/appapi.php?";
    axios .get(src,{
      params:{
        id=2,
        name="mary"
      }
    }).then(res => {
        console.log(res);
      }) .catch((err = {}));
  }
  mounted() {
    async function getData() {
      let data = await axios.get("");
      return data;
    }
    getData()
      .then((res = {}))
      .catch((err = {}));
  }

3. post方式传值

类似get传值。不同点是参数不在params中,而是直接传递

  • 给定src,参数在路径上
  mounted() {
    let src="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    axios .post(src).then(res => {
        console.log(res);
      }) .catch((err = {}));
  }
  • 参数不在路径上,post方法传两个参数,第二个参数传值
  mounted() {
    let src="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    axios .post(src,{    //直接传递  
        id=2,
        name="mary"      
    }).then(res => {
        console.log(res);
      }) .catch((err = {}));
  }

4. axios config配置方式

参数含义:

  • auth: auth指示应使用HTTP Basic auth,并提供凭据。
    // 这将设置一个“ Authorization”标头,覆盖所有现有标头
    // 您使用headers设置的Authorization自定义标题。
    // 请注意,只能通过此参数配置HTTP Basic身份验证。
    // 对于Bearer令牌等,请改用Authorization自定义标头。

  • method:These are the available config options for making requests. Only the url is required. Requests will default to GET if method is not specified.(只需要url,如果没有说明方式,则默认为get传值)

  • responseType indicates the type of data that the server will respond with
    // options are: ‘arraybuffer’, ‘document’, ‘json’, ‘text’, ‘stream’ (可能的选项)
    // browser only: ‘blob’(仅浏览器:“ blob”)

  • responseEncoding indicates encoding to use for decoding responses (解码响应的编码)

  • headers是要发送的自定义标题

  axios({
      method:"post",
      url:"http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1",
      data:{},//如果是get方式就省略这个data,因为get方式的数据在路径上
       timeout: 1000, // default is `0` (no timeout)
       auth: {//设置用户名和密码
    username: 'janedoe',
    password: 's00pers3cret'
  },
    responseType: 'json', // 返回的数据类型
  responseEncoding: 'utf-8' // 返回的字节编码
    }).then((res = {}))
  .catch((err = {}));

案例

http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1

  • 直接使用
mounted() {
    let src="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
    axios .get(src).then(res => {
        this.msg=res.data.result;
      }) .catch(((err) => {}));
  },
  data() {
    return {
      msg:[]
    };
  }
  • es6异步函数
  async function getData() {
      let data = await axios.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1");
      return data;
    }
    getData()
      .then((res => {
           this.msg = res.data.result;
      }))
      .catch((err => {}));
  • 请求配置

如果写上auth或者配置headers就会报错
Access to XMLHttpRequest at 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

axios({
      method: "get",
      url:
        "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1",
      // data:{},//如果是get方式就省略这个data,因为get方式的数据在路径上
      timeout: 1000, // default is `0` (no timeout)
      // `headers` are custom headers to be sent
  //headers: {'X-Requested-With': 'XMLHttpRequest'},
     // auth: {
     //   username: "janedoe",
      //  password: "s00pers3cret"
     // },

      responseType: "json", // 返回的数据类型
      responseEncoding: "utf-8" // 返回的字节编码
    })
      .then(res => {
        this.msg = res.data.result;
      })
      .catch(err => {});

页面循环绑定

<ul>
      <li v-for="(item,index) in msg" :key="index">
        {{item.title}}
      </li>
    </ul>

在这里插入图片描述

fetch实现jsonp跨域

1. 安装

cnpm install fetch-jsonp --save-dev

2. 引入
同上

import jsonp from "fetch-jsonp";

3. 使用

  1. jsonp跨域也返回promise对象
   let src = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=4";
      let test=jsonp(src);
      console.log(test);

在这里插入图片描述
通过官网了解到有两个then方法,第一个then输出不是最终结果,而是
在这里插入图片描述
所以在第一个then方法里将json方法执行后返回,第二个then方法后就能拿到最终数据,完整代码为

 let src =
      "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=4";
    jsonp(src).then(res => {
        return res.json();
      }).then(res => {
        this.msg=res.result;
      }).catch((err)=>{
        console.log(err);
      });
  1. 如果后台有要求的回调函数名称,则需要设置,否则走默认
    默认为
    在这里插入图片描述
    在代码中添加回调函数的相关信息:
  jsonp(src,{
      jsonpCallback:'callback',//回调函数的参数名称
      jsonpCallbackFunction:'getData'//回调函数名
    }).then(res => {
        return res.json();
      }).then(res => {
        this.msg=res.result;
      })

修改后的输出结果为
在这里插入图片描述

  1. 使用es6语法
let data = async () => await jsonp(src).then(res => res.json());
    data()
      .then(res => {
        console.log(res.result);
      })
      .catch(err => {
        console.log(err);
      });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值