1. Create a VUE project
1.1 New Project
New project
vue init webpack axios_resource
Then the specific Settings are as follows
Project name, project description, author,Runtime + Compiler Press Enter
Note that vue-Router and ESLint are installed here
Setup unit tests with Karma + Mocha? Setup E2E Tests with Nightwatch? I’ll just choose n for both
1.2 Installation Project Dependencies
cnpm install
1.3 installationaxios
The module
cnpm install axios --save
1.4 installationresource
The module
cnpm install vue-resource --save
1.5 Running Projects
cnpm run dev
The renderings are as follows
1.6 Modifying Page Content
SRC \ Components \Hello. Vue: SRC \ Components \Hello
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ author }}</h2>
</div>
</template>
<script>
export default {
name: 'hello',
data () {
return {
msg: 'Vue invokes netease Cloud Interface'.author: 'Ah mud monkey'}}}</script>
Copy the code
The renderings are as follows
2. Use axios
2.1 Let’s first modify the page to load some dynamic content
The template is modified as follows
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>{{ author }}</h2>
<ul v-for="music in musics">
<li>
{{ music.name }}
</li>
</ul>
</div>
</template>
Copy the code
The js part is modified as follows
<script> export default {name: 'hello', data () {return {MSG: 'hello', author: 'musics ', 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>Copy the code
And then save
Found an error page http://eslint.org/docs/rules/no-undef ‘axios’ is not defined
Axios is not defined because we did not import the AXIos module
Let’s import the AXIos module at the top of the JS section
import axios from 'axios'
The error message disappears after the AXIos module is loaded. An error message is displayed when you open the debugging console page
No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'http://localhost:8080' is therefore not allowed access.
Copy the code
Not allowed access indicates that our browser does not support cross-domain requests and we search a lot of information. Netease Cloud does not support cross-domain requests. The netease Cloud server does not return your request with the head field access-Control-Allow-Origin.
So what to do? B: Then we have to use an agent.
Here are three proxy methods: 1, remote proxy 2, PHP proxy 3, node proxy
3 the agent
3.1 Remote Proxy
The agent sends your request using a proxy interface written by someone else, so it doesn’t cross domains.
First we define a constant API_PROXY
const API_PROXY = 'https://bird.ioliu.cn/v1/?url='
Then concatenate the string in the AXIos request
axios.get(API_PROXY + 'http://music.163.com/api/playlist/detail?id=19723756')
Copy the code
The complete js code is as follows
<script> const API_PROXY = 'https://bird.ioliu.cn/v1/?url=' import axios from 'axios' export default { name: 'hello', data () {return {MSG: []}}, file: []}}, 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>Copy the code
The browser console page is displayed
Object {data: Object, status: 200, statusText: "OK", headers: Object, config: Object... }config: Objectdata: Objectheaders: Objectrequest: XMLHttpRequeststatus: 200statusText:"OK"__proto__: Object
Copy the code
The request is successful
Assigned to musics
this.musics = res.data.result.tracks
Copy the code
Found a page error
Uncaught (in promise) TypeError: Cannot set property 'musics' of undefined
Copy the code
Musics doesn’t define this because this is not referring to the current vue instance so let’s redefine this before we use Axios
var _this = this
Copy the code
Just use _this in Axios
Mounted part of code
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)
})
}
Copy the code
Open the console again, find no error, the requested data is also what we want
Modify the template again
Let’s add image data
The modified template is as follows
<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>
Copy the code
The complete code is as follows
<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 invokes netease Cloud Interface'.author: 'Ah mud monkey'.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>
Copy the code
The final effect is as follows
$curl = $curl
Using PHP curl to complete a proxy request
We have installed the vue-resource module. We need to load the vue-resource module in main.js
loading
import VueResource from 'vue-resource'
use
Vue.use(VueResource)
Curl curl curl curl curl curl curl curl curl curl curl curl curl
The complete index.js code is shown below
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
}
]
})
Copy the code
The vue-ResourceGet method is basically like Axios in that it doesn’t change much
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)
})
}
Copy the code
No parameter is required for the headers get method. If the request is sent in post mode, set access-Control-allow-origin: *
The complete code is 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 invokes netease Cloud Interface'.author: 'Ah mud monkey'.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>
Copy the code
Curl. PHP: curl. PHP: curl
// header('Content-type:text/html; Charset=utf-8');
header('Content-Type:text/json; charset=utf-8');// Set the type of file to return
header('Access-Control-Allow-Origin: *');// Set to allow all cross-domains
$id = '19723756'; //id
$va_url = 'http://music.163.com/api/playlist/detail?'; // Verify the url link address
$post_fields = "id={$id}"; // Post submits information string
$curl = curl_init(); // Initialize a cURL session
The curl_setopt() function is used to set the parameters to curl
curl_setopt($curl, CURLOPT_URL, $va_url); // Set the url link to verify login
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // Set the result to be stored in a variable, or output, default to 0 (output)
curl_setopt($curl, CURLOPT_POST, 1); // Simulate post submission
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); // Set the POST string
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); // Perform this cURL session
// echo "<pre>";
// print_r(json_decode($data));
echo $data;
// Check for errors
if(curl_errno($curl)) {
exit('Curl error: ' . curl_error($curl));
}
curl_close($curl); // Close the session
Copy the code
Curl request, you can go to the manual and the most important thing is to set header files to allow cross-domain
header('Access-Control-Allow-Origin: *');
Copy the code
If this is not set, the proxy is meaningless, otherwise the front end will still say cross domain
PHP file in your Apache/Nginx root directory, and the Apache/Nginx server is enabled.
3.3 nodejs agent
Similarly, create a new node. vue template and route to/Node
{
path: '/node'.name: 'Node'.component: Node
}
Copy the code
Index.js complete code
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
}
]
})
Copy the code
Set the agent
Open config/index.js to modify proxyTable: {}
proxyTable: {
'/api': {
target: 'http://music.163.com/api'.changeOrigin: true.pathRewrite: {
'^/api': ' '}}}Copy the code
The ‘/ API ‘in the first line refers to the virtual path target refers to the target address, which is the address of the actual API pathRewrite rule rewrite
Then modify the request address on the code page
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)
})
}
Copy the code
/api/playlist/detail? id=19723756
This address up here is essentially equal tohttp://localhost:8080/api
+/playlist/detail? id=19723756
Note that you must restart Node, because you must restart the configuration of Node to take effect
In the command window CTRL + C and then run CNPM run dev again, the command window will prompt
[HPM] Proxy created: /api -> http://music.163.com/api
[HPM] Proxy rewrite rule created: "^/api"~ >""
> Starting dev server...
Copy the code
The proxy is successful.
Then go to 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>
Copy the code
<script> export default {name: 'curl', data () {return {MSG: 'curl', author: 'musics ', 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>Copy the code
Making address github.com/pandoraxm/v…
Original link www.bear777.com/blog/vue-vu…