axios基础请求

{{ site.name }}

new Vue({

el: '#app',

data: {

info: null,

},

methods: {

//get请求,lambda形式

getTest: function () {

axios

.get('../json/json_demo.json')

// .get('https://www.runoob.com/try/ajax/json_demo.json')

.then(response => { this.info=response.data.sites; })

.catch(error => { alert(error); });

},

//post请求,方法回调形式

postTest: function () {

axios

.post('/user', {

firstName: 'Fred', // 参数 firstName

lastName: 'Flintstone' // 参数 lastName

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

},

//可以通过向 axios 传递相关配置来创建请求

requestTest: function () {

axios({

method: 'post',

url: 'http://bit.ly/2mTM3nY',

data: {

firstName: 'Fred',

lastName: 'Flintstone'

},

responseType: 'stream' //返回格式,例如图片

}).then(function (response) {

// response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))

})

},

//创建ajax实例,设置基础配置,搭配额外配置

ajaxTest: function () {

// 使用由库提供的配置的默认值来创建实例

// 此时超时配置的默认值是 `0`

const instance = axios.create({

baseURL: 'https://some-domain.com/api/',

timeout: 1000,

headers: {'X-Custom-Header': 'foobar'}

});

// 覆写库的超时默认值

// 现在,在超时前,所有请求都会等待 2.5 秒

instance.defaults.timeout = 2500;

// 为已知需要花费很长时间的请求覆写超时设置

instance.get('/12345',{

timeout: 5000

}).then(resp=>{}).catch(error=>{})

},

//axios同步请求(默认为异步请求)

async funA(){

var res = await axios.post('')//这里的res就是你axios请求回来的结果了

},

},

mounted: function () {

//执行多个并发请求

function getUserAccount() {

return axios.get('/user/12345');

}

function getUserPermissions() {

return axios.get('/user/12345/permissions');

}

axios.all([getUserAccount(), getUserPermissions()])

.then(axios.spread(function (acct, perms) {

// 两个请求现在都执行完成

}));

}

})

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐