一樣的咱們新建一個Node.vue
的模板和/node
的路由javascript
{
path: '/node',
name: 'Node',
component: Node
}
index.js 完整代碼html
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
}
]
})
設置代理vue
打開config/index.js
修改proxyTable: {}
部分
修改成java
proxyTable: {
'/api': {
target: 'http://music.163.com/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
第一行的'/api'
指的是虛擬路徑
target指的是目標地址,也就是實際api的地址
pathRewrite規則重寫node
而後在代碼頁面修改一下請求地址ios
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
vue-router
注意這裏必定要重啓一下node,由於你修改了node的配置必定要重啓才能生效npm
在命令符窗口ctrl + c
而後從新執行cnpm run dev
這時候,命令窗口會提示axios
[HPM] Proxy created: /api -> http://music.163.com/api
[HPM] Proxy rewrite rule created: "^/api" ~> ""
> Starting dev server...
說明代理成功api
而後訪問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>很早前在網上搜到的,近期纔開始看,已經忘了來源是哪了,若是做者看到,能夠留言地址,我再標註出處