在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>
当然如果你不想污染全局环境的话,可以这样做,将它挂载到原型上。
在控制台输入
npm run serve
运行WebServe 服务器,然后点击 按钮,查看控制台,效果大致如下。
遗憾的是,这种做法只能在 WebServer 行的通。
如果你,使用
npm run build
来编译成html文件来使用,是不行的。
会出现这种情况,所以你如果是使用build出来用的话,或者可以考虑jQuery。