vue用axios在页面直接调用接口完整版(代码源码)最新(四)

项目目录如下图

在这里插入图片描述

1.全局安装axios

(1)下载axios插件

npm install axios --save

(2)然后在main.js全局挂载,并且定义baseURL

import axios from 'axios'
Vue.prototype.$axios = axios
// 全局引入
axios.defaults.baseURL = "/api";

2.项目目录下创建vue.config.js,为了防止跨域,域名存放地,源码如下

module.exports = {
  publicPath: './',
  lintOnSave: false, 
  devServer: {
    port: 8089, // 启动端口
    open: false, // 启动后是否自动打开网页
    proxy: {
      '/api': {
        target: 'http://apis.juhe.cn', // 后端给的服务器地址
        secure: true, //接受对方是https的接口
        ws: true, // 是否启用websockets
        changeOrigin: true, //是否允许跨越
        pathRewrite: {
          '^/api': '/' //将你的地址代理位这个 /api 接下来请求时就使用这个/api来代替你的地址
        },
      }
    },
  }
}

3.页面直接调用源码如下

<template>
  <div class="home">
  </div>
</template>

<script>
export default {
      
      
  mounted () {
      
      
    this.getList()
  },
  methods: {
      
      
    getList () {
      
      
      this.$axios({
      
                                             //接口意思就是:域名(在vue.config.js存放后台给的服务器域名) + 请求地址 = 接口
        url: '/tyfy/query',                               // 请求地址 
        methods: 'get',                                   // 请求方式
        params: {
      
                                               // 需要传的参数
          key: '这里key就不透漏了,自己可以去聚合数据免费申请~',
          word: '希望'
        }
      }).then(item => {
      
      
        console.log(item, 'itemmm');
      })
    }
  },
  components: {
      
      
  }
}
</script>

4.最终得到接口效果如下图

在这里插入图片描述

感觉文章好的话记得点个心心和关注和收藏,有错的地方麻烦指正一下,如果需要转载,请标明出处,多谢!!!

猜你喜欢

转载自blog.csdn.net/m0_49714202/article/details/124946191