登录  /  注册
博主信息
博文 87
粉丝 1
评论 0
访问量 54620
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
vue实战使用ajax请求后台数据
阿杰
原创
2399人浏览过

Axios的安装和引入

  1. 使用npm安装:
    1. $npm install axios -S
  2. 在vue项目公共文件(我这里是main.js文件)中引入:
    1. import axios from "axios";
  3. axios跟很多第三方模块不同的一点是它不能直接使用use方法,而是用下面这种方法:
    1. Vue.prototype.$axios = axios;
  4. 这样呢在methods里用到的时候直接用this.$axios来调用它:
    1. this.$axios.get(接口地址).then(function(respon){}).catch(function(error){})

axios.get

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    2. params:{
    3. video_id:4
    4. }
    5. }).then(res=>{
    6. console.log(res);
    7. }).catch(function(error){
    8. })

axios.post

  1. 通过params选项来传递参数的格式是 axios.get(‘url’,{params:{key:value}}).then() ;

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",{
    2. params:{
    3. token:'050e26b301245052c8ef807677025bb2',
    4. com_id:19792
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })

    会出现跨域问题,因为axios本身并不支持发送跨域的请求

    解决方案:通过字符串的方式发送数据

    1. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",'token=050e26b301245052c8ef807677025bb2&com_id=19792').then(res=>{
    2. console.log(res.data.data);
    3. }).catch(function(error){
    4. })

用qs来解决post跨域问题

  1. 安装qs:
    1. npm install --save axios vue-axios qs
    2. import qs from 'qs' qs 用来解决vue中post请求以 a=a&b=b 的格式
  2. main.js 内容:
    1. import axios from "axios"
    2. import qs from "qs"
    3. Vue.prototype.$axios = axios
    4. Vue.prototype.$qs = qs
  3. 需要的页面请求接口时 get 和post 两种方法:

    1. getbuyer:function(){
    2. this.$axios.get("http://api.xdclass.net:8081/pub/api/v1/web/list_buyer",{
    3. params:{
    4. video_id:4
    5. }
    6. }).then(res=>{
    7. console.log(res);
    8. }).catch(function(error){
    9. })
    10. },
    11. getData:function(){
    12. this.$axios.post("https://nmapi.rdxsaj.com/v1/Indexc",
    13. this.$qs.stringify({
    14. token:'050e26b301245052c8ef807677025bb2',
    15. com_id:19792
    16. })
    17. ).then(res=>{
    18. console.log(res);
    19. }).catch(function(error){
    20. })
    21. }

    请求成功

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学