VUE2—axios的使用及代理

概述

在使用axios请求后台接口的进候,可能会遇到跨域问题。可以设置代理来解决这个问题。

安装axios

cnpm install axios --save-dev

配置代理

配置文件:vue.config.js

module.exports = defineConfig({
  publicPath: './',   //打包路径
  outputDir: 'dist',  //输出文件目录
  lintOnSave: true, //配置打开eslint,默认即为打开
  transpileDependencies: true,

  devServer: {
    open: false,      //自动打开浏览器
    host: '0.0.0.0',
    port: '8080',
    https: false,     //是否为https协议
    proxy: {
      '/api': {
        target: 'http://localhost:9099',
        changeOrigin: true,
        secure: false,  //如果使用https请设置为true
        logLevel: 'debug'
      }
    }
  }
})

注意:要求后端的接口必须以api开头,例如后台接口为“http://localhost:9088/api/amis/getUserTemplates”,那么在axios中配置的请求地址为:/api/amis/getUserTemplates

配置axios

<script>
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String,
    content: {
      type: String,
      defaut: ""
    }
  },
  methods: {
    viewMais1() {
      let that = this;
      axios.post('/api/amis/getUserTemplates',{
            responseType: 'json',
            "userOriginCode": "user001"   #请求参数
        })
        .then(function (response){
          console.log(response.data.userTemplateList);
          var templateArray = response.data.userTemplateList;
          that.$refs.iframe.contentWindow.iframeTest(templateArray);
        });
    }
  }
}
</script>

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注