新建项目javascript
vue init webpack axios_resource
php
而后具体设置以下html
项目名称,项目描述,做者,Runtime + Compiler 回车便可前端
注意这里要安装vue-router和ESLintvue
而后Setup unit tests with Karma + Mocha?
和Setup e2e tests with Nightwatch?
都选择n便可java
cnpm install
node
axios
模块cnpm install axios --save
webpack
resource
模块cnpm install vue-resource --save
ios
cnpm run dev
nginx
效果图以下
咱们先修改一下页面内容 src\components\Hello.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ author }}</h2>
</div>
</template>
<script> export default { name: 'hello', data () { return { msg: 'vue调用网易云接口', author: '泥猴啊' } } } </script>
复制代码
效果图以下
模板修改以下
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ author }}</h2>
<ul v-for="music in musics">
<li>
{{ music.name }}
</li>
</ul>
</div>
</template>
复制代码
js部分修改以下
<script>
export default {
name: 'hello',
data () {
return {
msg: 'vue调用网易云接口',
author: '泥猴啊',
musics: []
}
},
mounted: function () {
axios.get('http://music.163.com/api/playlist/detail?id=19723756')
.then(function (res) {
console.log(res)
}, function (error) {
console.log(error)
})
}
}
</script>
复制代码
而后保存
发现页面有一个报错 http://eslint.org/docs/rules/no-undef 'axios' is not defined
axios没有定义,是由于咱们没有导入axios模块的缘由
咱们在js部分顶部导入一下axios模块
import axios from 'axios'
加载axios模块以后错误提示消失了。 打开调试页面console界面 发现有一个报错
No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://localhost:8080' is therefore not allowed access.
复制代码
这里的not allowed access
就是提示咱们浏览器不支持跨域请求,搜索了不少资料,网易云不支持跨域请求的(网易云的服务器在返回你的请求中没有Access-Control-Allow-Origin这个head字段)。
那怎么办呢? 那咱们只能使用代理了。
下面将介绍3种代理方式:1,远程代理 2,php代理 3,node代理
就是利用别人写好的代理接口,代理发送你的请求,这样就不会跨域了。
首先咱们定义一个常量API_PROXY
const API_PROXY = 'https://bird.ioliu.cn/v1/?url='
而后在axios
请求里面拼接一下字符串
axios.get(API_PROXY + 'http://music.163.com/api/playlist/detail?id=19723756')
复制代码
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 () {
axios.get(API_PROXY + 'http://music.163.com/api/playlist/detail?id=19723756')
.then(function (res) {
console.log(res)
}, function (error) {
console.log(error)
})
}
}
</script>
复制代码
打开浏览器console
界面
Object {data: Object, status: 200, statusText: "OK", headers: Object, config: Object…}config: Objectdata: Objectheaders: Objectrequest: XMLHttpRequeststatus: 200statusText: "OK"__proto__: Object
复制代码
请求成功
赋值给musics
this.musics = res.data.result.tracks
复制代码
发现页面有个报错
Uncaught (in promise) TypeError: Cannot set property 'musics' of undefined
复制代码
musics没有定义 由于这里,this的指向不是当前的vue实例 那咱们在使用axios
以前从新,定义一下this
var _this = this
复制代码
在axios
使用_this
就行了
mounted部分代码
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)
})
}
复制代码
再打开控制台,发现没有报错,请求的数据也是咱们想要的
再次修改一下模板
咱们再增长图片数据
修改好的模板以下
<template>
<div class="hello">
<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>
复制代码
完整代码以下
<template>
<div class="hello">
<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> 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>
复制代码
最后效果图以下
这里演示vue-resource的写法 + php curl 完成代理请求
前面咱们安装了vue-resource
模块,咱们要在main.js
加载一下vue-resource
模块
加载
import VueResource from 'vue-resource'
使用
Vue.use(VueResource)
为了不和以前页面混淆,咱们从新新增一个curl页面,路由一样新增长一条'/curl'的路由
index.js 完整代码以下
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '@/components/Hello'
import Curl from '@/components/Curl'
import VueResource from 'vue-resource'
Vue.use(Router)
Vue.use(VueResource)
export default new Router({
routes: [
{
path: '/',
name: 'Hello',
component: Hello
},
{
path: '/curl',
name: 'Curl',
component: Curl
}
]
})
复制代码
其实vue-resource
get方法基本上和axios
很像,基本上没有太多变更
mounted: function () {
this.$http.get('http://localhost/curl.php', {}, {
headers: {
},
emulateJSON: true
}).then(function (res) {
this.musics = res.data.result.tracks
console.log(this.musics)
}, function (error) {
console.log(error)
})
}
复制代码
headers get方法里面不用填写参数,若是是post方式发送请求 则要设置Access-Control-Allow-Origin: *
完整代码以下 src\components\Curl.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('http://localhost/curl.php', {}, { headers: { }, emulateJSON: true }).then(function (res) { this.musics = res.data.result.tracks console.log(this.musics) }, function (error) { console.log(error) }) } } </script>
复制代码
固然了,最重要的是curl.php这个部分代码怎么写了 curl.php 完整代码
<?php
// header('Content-type:text/html;Charset=utf-8');
header('Content-Type:text/json;charset=utf-8');//设置返回文件的类型
header('Access-Control-Allow-Origin: *');//设置容许全部跨域
$id = '19723756'; //id
$va_url = 'http://music.163.com/api/playlist/detail?'; //验证的 url 连接地址
$post_fields = "id={$id}"; //post提交信息串
$curl = curl_init(); //初始化一个cURL会话,必有
//curl_setopt()函数用于设置 curl 的参数,其功能很是强大,具体看手册
curl_setopt($curl, CURLOPT_URL, $va_url); //设置验证登录的 url 连接
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设置结果保存在变量中,仍是输出,默认为0(输出)
curl_setopt($curl, CURLOPT_POST, 1); //模拟post提交
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); //设置post串
//避免https请求报错 Curl error: SSL certificate problem: unable to get local issuer certificate
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl); //执行此cURL会话,必有
// echo "<pre>";
// print_r(json_decode($data));
echo $data;
//检查是否有错误
if(curl_errno($curl)) {
exit('Curl error: ' . curl_error($curl));
}
curl_close($curl); //关闭会话
复制代码
curl请求的话就解释了,你们能够去看手册 最重要的是设置头文件容许跨域
header('Access-Control-Allow-Origin: *');
复制代码
若是没有设置这个的话,代理也是没有意思的,否则前端仍是会提示跨域
固然啦,你要把curl.php这个文件丢在你apache或者nginx根目录,同时apache或者nginx服务器也别忘记启用了哦。
一样的咱们新建一个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 Curl from '@/components/Curl'
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: '/curl',
name: 'Curl',
component: Curl
},
{
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>
复制代码
github地址 github.com/pandoraxm/v…