Vue-axios数据交互

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue-axios数据交互

程序猿-张益达   2022-05-28 我要评论

1、安装axios

  • 打开cmd命令行工具
  • cd到项目目录
  • 输入以下命令
npm install axios

提示安装完成以后,打开main.js

输入以下代码:

import axios from 'axios'

接着在底下输入:

Vue.prototype.$axios = axios

配置就完事了

2、axios的使用

this.$axios({
        method: 'post',//交互方式
        url: '/api/ImgHandle',//url地址
        data: {page: page}//需要交互的数据
      }).then((res) => {
        console.log(res)//成功   res为返回的结果
      }).catch((error) => {
        console.log(error)//失败   打印异常
      })

3、讲一下代理proxyTable的使用

一般在开发时,地址都在本地,会出现跨域报错,报错示例如下:

Failed to load http://192.168.1.111:8888/console/good/front/classList:
 Response to preflight request doesn’t pass access control 
check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
 Origin ‘http://localhost:8081’ is therefore not allowed access. 
 If an opaque response serves your needs, 
 set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

如果后端不修改,那就前端操作修改一下:

  • 找到 config/index.js
  • 找到 proxyTable进行修改
 proxyTable: {
      '/api': {  //使用"/api"来代替"http://www.xxx.com/"
        target: 'https://www.xxx.com/', //源地址
        changeOrigin: true, //改变源
        pathRewrite: {
          '^/api': 'https://www.xxx.com/' //路径重写
        }
      }
    },

然后重新运行一下,即可生效,操作失败就再检查一下代码

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们