Axios、axios拦截器、fetch-jsonp ——0807

it2026-03-28  4

一、axios——vue数据请求插件

用来请求 cross 跨域的 api 接口的插件。

1、axios的使用

1、安装axios:

cnpm install --save-dev axios

2、引入并使用

全局引入并关联、使用

main.js里边:

import Axios from 'axios' Vue.prototype.$axios=Axios;

组件里边使用:

//组件挂载完成之后进行数据请求 mounted(){ this.$axios .get("") //请求路径 .then((res) => { console.log(res); //返回的数据 }) .catch((error) => { console.log(error); }) .finally(() => { console.log("最后处理"); }); }

也可以发送post请求并传参,具体用法参考 npmjs 官网。

2、axios 拦截器

可以通过封装的axios拦截器对ajax请求和响应做相应的处理,统一处理错误及配置请求信息。

axios拦截器有两种:请求拦截器 和 响应拦截器。

具体操作如下: 在src根目录下新建文件axios.js,内容如下:

// 封装axios 拦截器 //引入axios import Axios from 'axios'; //设置默认的host Axios.defaults.baseURL = "http://www.maodou.com:8080"; //设置请求拦截器 Axios.interceptors.request.use((config) => { console.log(config); //ajax请求配置 //...在发送请求之前做些什么 return config; }, (error) => { //...对请求错误做些什么 return Promise.reject(error); }); //设置响应拦截器 Axios.interceptors.response.use((response) => { console.log(response); //可以对数据做处理 return response; }, (error) => { //对响应错误做些什么 return Promise.reject(error); });

在main.js中进行引入:

//全局引入 import Axios from 'axios' import './Axios/axios'; Vue.prototype.$axios=Axios;

在组件中使用: 使用的时候 url 写半路径,因为请求拦截器里边已经设置过 baseURL。

this.$axios({ method: "get", url: "/user", }) .then((res) => { console.log(res); }) .catch((error) => { console.log(error); });

二、fetch-jsonp

用来请求 jsonp 跨域的 api 接口 的插件。

JSONP only supports GET method, same as fetch-jsonp.

1、fetch-jsonp 的使用

1、安装fetch-jsonp

cnpm install --save-dev fetch-jsonp

2、全局引入 fetch-jsonp,并关联到vue原型上:

//引入fetch-jsonp import Fetch from 'fetch-jsonp' Vue.prototype.$fetch=Fetch;

3、在组件中使用

this.$fetch("/", { jsonpCallback: "getData", //设置jsonp的回调函数名称 timeout: 2000, }) .then((res) => { return res.json(); //第一个then是固定的 }) .then((res) => { console.log(res); //返回的数据 }) .catch((error) => { console.log(error); //抓异常 });

2、fetch 拦截器

axios有自己的拦截器方法,可以直接调方法;fetch-jsonp 没有,可以通过类来封装。

实现代码参考

最新回复(0)