Axios发送get、post请求,获取并处理返回值

一:axios是什么。
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
二:axios特点。
1.从浏览器中创建 XMLHttpRequests
2. 从 node.js 创建 http 请求
3. 支持 Promise API
4. 拦截请求和响应 (就是有interceptor)
5. 转换请求数据和响应数据
6. 取消请求
7. 自动转换 JSON 数据
8. 客户端支持防御 XSRF
三:安装配置。
1,使用 npm(当大量使用axios时,可以将axios作为vue的插件全局使用):
$ npm install axios
2,使用 cdn:

在script标签中引入:https://unpkg.com/axios/dist/axios.min.js

3,.在main.js中引入文件

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

axios.defaults.baseURL='/api'

四:get请求方法。
方法一:

axios.get('/user?ID=0909')
  .then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

方法二:

axios.get('/user', {
    params: {
      ID: 0909
    }
  }).then(function (response) {
    console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

五;post请求方法。

axios.post('/user', {
    firstName: 'frist',
    lastName: 'last'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

六:在生命周期mounted里发起请求。

mounted(){
	//get
	this.axios.get('url').then(res => {
		console.log('success')   //调用成功
	},res => {
		console.log('error')   //调用失败
	})
	//post
	this.axios.post('url').then(res => {
		console.log('success')   //调用成功
	},res => {
		console.log('error')   //调用失败
	})
}

实例:

<template>
<div>
    <div class="topAll">
        <div class="detailsTop">
            <img :src="main.image">
        </div>
        <div class="detailstitle">
            {{main.title}}
            <div class="subTitle">{{main.image_source}}</div>
        </div>
        <div v-html="main.body" class="dParagraph"></div>
    </div>
</div>
</template>

<script>
export default {
    data() {
        return {
            main:''
        }
    },
    mounted:function(){
        this.axios.get('news/3892357').then(res => {
            this.main = res.data
        })
    }
}
</script>
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值