axios用于浏览器和node.js中发送ajax请求

一、axios的作用
axios是独立于vue的一个项目,可以用于浏览器和node.js中发送ajax请求

二、axios实例
创建axios_pro文件夹
1、复制js资源

vue.min.js
axios.min.js

2、创建 axios.html
3、引入js

<script src="vue.min.js"></script>
<script src="axios.min.js"></script>

4、启动课程中心微服务
5、编写js

<script>
    new Vue({
        el: '#app',
        data: {
            teacherList: []
        },
        methods: {
​
            getTeacherList(){
                axios.get('http://localhost:8110/admin/edu/teacher/list').then(response => {
                    console.log(response)
                    this.teacherList = response.data.data.items
                }).catch(error=>{
                    //失败
                    console.log(error)
                })
            }
        }
    })
</script>

6、html渲染数据

<div id="app">
    <button @click="getTeacherList()">访问</button>
​
    <table>
        <tr v-for="item in teacherList">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
        </tr>
    </table>
</div>

7、跨域
为什么会出现跨域问题?

出于浏览器的同源策略限制:
所谓同源(即指在同一个域)就是两个地址具有相同的协议(protocol),主机(host)和端口号(port)
同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。
同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能。
解决跨域问题:

@CrossOrigin //解决跨域问题

8、使用生命周期函数
和methods一个级别

created () {
    this.getTeacherList()
},

9、业务分层的简单实现

// 初始化axios设置,返回一个函数引用
initRequest () { 
    return axios.create({
        baseURL: 'http://localhost:8110', // api 的 base_url
        timeout: 5000 // 请求超时时间
    })
},
​
//api访问模块
teacherListApi (){
    let request = this.initRequest()
    return request({
        url: '/admin/edu/teacher/list',
        method: 'get'
    })
},
​
    
//获取讲师列表
getTeacherList2() {
    console.log('发送ajax请求2......')
    this.teacherListApi().then(response => {
        console.log(response)
        var result = response.data //r对象
        this.teacherList = result.data.items
    })
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值