如何使用Vue-axios进行数据交互

axios重要性不说了
直接上代码

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.

网上有很多博客转载来转载去,都是转载的,很难找到正确的解决方法

一般正确的解决方法有两个
首先,后端处理header

header('Access-Control-Allow-Origin:*');//允许所有来源访问 
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式 

如果后端不修改,那就前端操作修改一下
找到 config/index.js
找到 proxyTable进行修改

 proxyTable: {
      '/api': {  //使用"/api"来代替"http://www.xxx.com/"
        target: 'https://www.xxx.com/', //源地址
        changeOrigin: true, //改变源
        pathRewrite: {
          '^/api': 'https://www.xxx.com/' //路径重写
        }
      }
    },

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

你可能感兴趣的:(VUE)