<script>
const API_PROXY = 'https://bird.ioliu.cn/v1/?url='
import axios from 'axios'
export default {
name: 'hello',
data () {
return {
msg: 'vue調用網易雲接口',
author: '泥猴啊',
musics: []
}
},
mounted: function () {
var _this = this
axios.get(API_PROXY + 'http://music.163.com/api/playlist/detail?id=19723756')
.then(function (res) {
_this.musics = res.data.result.tracks
console.log(_this.musics)
}, function (error) {
console.log(error)
})
}
}
</script>
同樣的我們新建一個Node.vue
的模板和/node
的路由
{
path: '/node',
name: 'Node',
component: Node
}
index.js 完整代碼
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Node from '@/components/Node'
import VueResource from 'vue-resource'
Vue.use(Router)
Vue.use(VueResource)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},
{
path: '/node',
name: 'Node',
component: Node
}
]
})
設置代理
打開config/index.js
修改proxyTable: {}
部分
修改為
proxyTable: {
'/api': {
target: 'http://music.163.com/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
第一行的'/api'
指的是虛擬路徑
target指的是目標地址,也就是實際api的地址
pathRewrite規則重寫
然后在代碼頁面修改一下請求地址
mounted: function () {
this.$http.get('/api/playlist/detail?id=19723756', {}, {
headers: {
},
emulateJSON: true
}).then(function (res) {
this.musics = res.data.result.tracks
console.log(this.musics)
}, function (error) {
console.log(error)
})
}
/api/playlist/detail?id=19723756
上面的這個地址其實就等於http://localhost:8080/api
+/playlist/detail?id=19723756
注意這里一定要重啟一下node,因為你修改了node的配置一定要重啟才能生效
在命令符窗口ctrl + c
然后重新執行cnpm run dev
這時候,命令窗口會提示
[HPM] Proxy created: /api -> http://music.163.com/api
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...
說明代理成功
然后訪問http://localhost:8080/#/node
就能看到效果了
完整代碼 src\components\Node.vue
<template>
<div class="curl">
<h1>{{ msg }}</h1>
<h2>{{ author }}</h2>
<ul v-for="music in musics">
<li>
{{ music.name }}
</li><br>
<li>
<img :src="music.album.picUrl" style="width:200px;">
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'curl',
data () {
return {
msg: 'vue調用接口',
author: '學習啦',
musics: []
}
},
mounted: function () {
this.$http.get('/api/playlist/detail?id=19723756', {}, {
headers: {
},
emulateJSON: true
}).then(function (res) {
this.musics = res.data.result.tracks
console.log(this.musics)
}, function (error) {
console.log(error)
})
}
}
</script>
很早前在網上搜到的,近期才開始看,已經忘了來源是哪了,如果作者看到,可以留言地址,我再標注出處