Vue 使用Axios 跨域问题

在Vue 项目学习的过程中遇到了,Axios跨域的问题。
有很多这方面的解决博文,但大多都是 vue 3以前的并不适合。
也有Vue3的,但都太难懂了不够直接、

vue安装 axios

npm install axios   

接着在项目中添加 vue.config.js 配置文件
在这里插入图片描述
vue.config.js
我这里以百度音乐的接口为示例

module.exports = {
    devServer: {
        proxy: {
            '/music': {
                target: 'http://tingapi.ting.baidu.com',        // 目标主机      
                ws: true,
                changeOrigin: true,
                pathRewrite:{
                    '^/music': ''
                }
            }
        } 
    }
}

摘选自 官方 CLI 配置文档的记录
CLI 配置连接
在这里插入图片描述

接着我们在组件中使用 axios 进行测试

App.vue

<template>
  <div id="app">
    <p> {{ message }} </p>
    <button @click="buttonAxios"> {{buttonText}} </button>
  </div>
</template>

<script>

import Axios from 'axios'       // 导入 axios库

export default {
  name: 'App',
  data:function(){
    return {
      message:'hello word',
      buttonText:'Click Me'
    }
  },
  methods:{
    buttonAxios:function(){

      // 获取百度音乐列表
      Axios.get('music/v1/restserver/ting', {
        params:{
          method: 'baidu.ting.billboard.billList',
          type: 1,
          size: 10,
          offset: 0
        }
      }).then(musicResult => {
        console.dir(musicResult);
      }).catch(musicError => {
        console.dir(musicError);
      });
      
    }
  }
}
</script>

<style>

</style>

当然如果你不想污染全局环境的话,可以这样做,将它挂载到原型上。

CookBook连接

在这里插入图片描述
在控制台输入

npm run serve

运行WebServe 服务器,然后点击 按钮,查看控制台,效果大致如下。
在这里插入图片描述

遗憾的是,这种做法只能在 WebServer 行的通。
如果你,使用

npm run build

来编译成html文件来使用,是不行的。
会出现这种情况,所以你如果是使用build出来用的话,或者可以考虑jQuery。
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值