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

axios实现cros跨域

网站 www.npmjs.com,能搜索到插件安装及使用方式

axios最终返回的是promise对象

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它自己具备如下特征:

从浏览器中建立 XMLHttpRequest

从 node.js 发出 http 请求

支持 Promise API

拦截请求和响应

转换请求和响应数据

取消请求

自动转换JSON数据

客户端支持防止 CSRF/XSRFjavascript

测试网址

get请求地址: http://vue.studyit.io/api/getlunbo

post请求地址:http://vue.studyit.io/api/post

jsonp请求地址:http://vue.studyit.io/api/jsonp

使用

1. 安装php

cnpm install axios --save-devvue

2. 引入java

原型链方法-全局使用

import axios from 'axios'

Vue.prototype.axios=axios

输出node

mounted() {

console.log(this.axios);

}

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

ƒ 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'

输出es6

mounted() {

console.log(axios);

}

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

2. get方式传值npm

给定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方式传值json

相似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 => {});

页面循环绑定

  • {{item.title}}

4f1e8b3d27924b939438c5978e3c5aa1.png

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

b5137f13b6e26aa40af8bf3a6e1d85a2.png

经过官网了解到有两个then方法,第一个then输出不是最终结果,而是

75bfdda433e1be01acd8736d931e055e.png

因此在第一个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);

});

若是后台有要求的回调函数名称,则须要设置,不然走默认

默认为

0746d9d272adb9e30dabc16c79988828.png

在代码中添加回调函数的相关信息:

jsonp(src,{

jsonpCallback:'callback',//回调函数的参数名称

jsonpCallbackFunction:'getData'//回调函数名

}).then(res => {

return res.json();

}).then(res => {

this.msg=res.result;

})

修改后的输出结果为

7c318dd41d85c5038fe58f27a0080463.png

使用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、付费专栏及课程。

余额充值