axios实现cros跨域
- 网站 www.npmjs.com,能搜索到插件安装及使用方式
- axios最终返回的是promise对象
- axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
从浏览器中创建 XMLHttpRequest
从 node.js 发出 http 请求
支持 Promise API
拦截请求和响应
转换请求和响应数据
取消请求
自动转换JSON数据
客户端支持防止 CSRF/XSRF
- 测试网址
- 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. 使用
- 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);
});
- 如果后台有要求的回调函数名称,则需要设置,否则走默认
默认为
在代码中添加回调函数的相关信息:
jsonp(src,{
jsonpCallback:'callback',//回调函数的参数名称
jsonpCallbackFunction:'getData'//回调函数名
}).then(res => {
return res.json();
}).then(res => {
this.msg=res.result;
})
修改后的输出结果为
- 使用es6语法
let data = async () => await jsonp(src).then(res => res.json());
data()
.then(res => {
console.log(res.result);
})
.catch(err => {
console.log(err);
});