vue中axios调用接口和用node.js跨域

 <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

请求成功3

就能看到效果了 
完整代码 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>

很早前在网上搜到的,近期才开始看,已经忘了来源是哪了,如果作者看到,可以留言地址,我再标注出处
posted @ 2018-02-28 15:25  susanws  阅读(2044)  评论(0编辑  收藏  举报