4. Data request through axios
vue.js ajax is not available by default.
So when using vue, we usually use axios plug-in to realize the data interaction between ajax and back-end server.
Note that axios are essentially ajax encapsulation of javascript, so they are limited by the same origin policy.
plug-in unit: http://www.axios-js.com/
Download address:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios provides two common ways to send requests: axios.get() and axios.post() .
Add post
delete
put/patch
Check get
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <button @click="get_data">click</button> </div> <script> var vm = new Vue({ el: "#app", data: {}, methods: { get_data() { // Send get request // axios.get('http://baidu.com', { // params: { // //Key value pair of query string // username: 'zbb' // } // }, { // //Request header information // Compant: "oldboy" // }); // Send post request axios.post("http://www.baidu.com", { username: "xiaoming", password: "123456", }, { // Request header information }).then((response) => { // Code executed by axios after the request succeeds // response.data Response data }).catch(function (error) { // Code executed by axios when an unexpected error occurs in the request // Error error object (local) // error.response Response error message from server }); } } }); // Anonymous function // var func = function(response){ // //Function code // }; // // //Arrow function // var func = (response)=>{ // //Function code // } </script> </body> </html>
summary
//Send get request //Parameter 1: required, string, url address of the requested data interface, for example, request address: http://www.baidu.com?id=200 //Parameter 2: optional, json object, parameter to be provided to data interface //Parameter 3: optional, json object, request header information //Send post requests, parameters and usage and axios.get() same. //Parameter 1: required, string, url address of the requested data interface //Parameter 2: required, json object, parameter to be provided to data interface. If there is no parameter, you must use {} //Parameter 3: optional, json object, request header information
4.1 json
json is the acronym of JavaScript Object Notation. The word means javascript object representation. Here, json refers to a data format similar to javascript object.
The function of json is to transfer data between different system platforms or programming languages.
4.1.1 json data syntax
The json data object is similar to the object in JavaScript, but there is no function method in the value corresponding to its key. The value can be a normal variable, does not support undefined, and the value can also be an array or json object.
//json object of native js var obj = { age:10, sex: 'female', work:function(){ return "study hard", } } //There is no method for the object format and json data format of json data, only attributes: { "name":"tom", "age":18 } //Array format of json data: ["tom",18,"programmer"] Complex json format data can contain the writing methods of objects and arrays. { "name": "Xiaoming", "age":200, "is_delete": false, "fav":["code","eat","swim","read"], "son":{ "name": "Xiao Xiaoming", "age":100, "lve":["code","eat"] } } //Array structure can also be used to transfer data as json. json data can be saved in a. json file. Generally, there is only one json object in it.
Summary:
- The suffix of the json file is. json
- json files generally hold a single json data
- The property of json data cannot be a method or undefined. The property value can only be: value [integer, decimal, Boolean], string, json and array
- json data uses only double quotation marks, each attribute member is separated by commas, and the last member has no commas.
{
"name": "Xiaoming",
"age":200,
"fav":["code","eat","swim","read"],
"son":{
"name": "Xiao Xiaoming",
"age":100
}
}
Tool: postman can be used to test the data interface of development.
4.1.2 js on data conversion method provided in JS
javascript provides a JSON object to manipulate the data transformation of JSON data
Method parameter return value description
stringify json object string json object to string
parse string json object json data in string format is converted to json object
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <script> var data = { "name":"xiaopmiong", "age":13, "sex":true }; // Converting json objects to json strings json_str = JSON.stringify(data); console.log() // Replace json string with json object data_str = '{"name":"xiaopmiong","age":13,"sex":true}'; json_obj = JSON.parse(data_str); console.log(json_obj); </script> </body> </html>
4.2 ajax
ajax, commonly known as "ajax" in Chinese, is a shorthand for "Async Javascript And Xml" in English.
The function of ajax: ajax can let js instead of browser send http request to the back-end program, communicate with the back-end program, operate data and information without the user's knowledge, so as to realize the local refresh data / no refresh update data of the page.
Therefore, ajax is a very common technology in development, which is mainly used to operate the data interface provided by the back end, so as to realize the separation of the front and back end of the website.
The principle of ajax technology is to instantiate the XMLHttpRequest object of js, and use the built-in method provided by this object to communicate with the backend.
4.2.1 data interface
Data interface, also known as api interface, means that the backend provides the url address of operation data / function to the client.
The client applies for the operation data from the url address provided by the server through the request [general operation: add, delete, check and change]
At the same time, most of the data interfaces are not handwritten, but generated by function library / framework.
4.2.3 use of Ajax
The use of ajax must be used together with the server-side program, but at present, we first learn the use of ajax, so we do not involve the writing of the server-side python code for the time being. Therefore, we can use the data interface written by others to call.
jQuery encapsulates ajax as a function $. ajax(), which we can use directly to execute ajax requests.
Interface address
Weather interface http://wthrcdn.etouch.cn/weather_mini?city = city name
Music interface search http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query= Song title
Music information interface http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid= Music ID
Write code to obtain the data provided by the interface:
vue version:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <button @click="get_data">click</button> </div> <script> var vm = new Vue({ el: "#app", data: {}, methods: { get_data() { axios.get("http://wthrcdn.etouch.cn/weather_mini?city = Beijing "{ }).then(response => { // success console.log(response.data); }).catch(error => { // report errors console.log(error.response); }); } } }) </script> </body> </html>
4.2.4 homology strategy
Homology policy is a kind of security mechanism for browser to protect user information security. The so-called homology refers to whether the protocol, domain name (IP) and port are the same between the two addresses of communication (such as server interface address and browser client page address). The client script [javascript] of different sources does not have permission to read and write the information of the other party without explicit authorization.
ajax is essentially javascript, which is the script language running in the browser, so it will be limited by the browser's homology policy.
Front end address: http://www.oldboy.cn/index.html Is it homologous
http://www.oldboy.cn/user/login.html Yes, the protocol, domain name and port are the same
http://www.oldboy.cn/about.html Yes, the protocol, domain name and port are the same
https://www.oldboy.cn/user/login.html No protocol is different (HTTPS and http)
http:/www.oldboy.cn:5000/user/login.html No different ports (5000 and 80)
http://bbs.oldboy.cn/user/login.html No different domain name (BBS and www)
The same origin policy aims at ajax interception, code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script src="js/axios.js"></script> </head> <body> <div id="app"> <button @click="get_music">Click to get weather</button> </div> <script> let vm = new Vue({ el:"#app", data:{}, methods:{ get_music(){ axios.get("http://tingapi.ting.baidu .com/v1/restserver/ting?method= baidu.ting.search . catalogsug & Query = my Chinese heart ") .then(response=>{ console.log(response); }).catch(error=>{ console.log(error.response) }); } } }) </script> </body> </html>
The above code runs with the following errors:
Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Above error, keyword: access control allow origin
As long as this keyword appears, access is limited. There is a problem of blocking the same origin policy.
4.2.5 CORS of Ajax cross domain (cross source) solution
ajax cross domain (cross source) solution: backend authorization [CORS], jsonp, server agent
CORS is a W3C standard, full name is "cross domain resource sharing". It allows browsers to send Ajax requests to cross source back-end servers, thus overcoming the limitation that Ajax can only be used from the same source.
The implementation of CORS mainly relies on the response header information set in the response data of the back-end server, which is returned by access control allow origin.
django View of def post(request): response = new Response() response .headers["Access-Control-Allow-Origin"] = "http://localhost:63342" return response; // Set the following contents in the response line information: Access-Control-Allow-Origin: ajax Domain name address Access-Control-Allow-Origin: www.oldboy.cn # Indicates only allowed www.oldboy.cn ajax cross domain access of domain name client // *Indicates any source, indicating that ajax of clients under any source is allowed to access the current server information Access-Control-Allow-Origin: *
Summary:
-
Homology policy: a browser security mechanism to protect user data.
Browsers restrict ajax access to data addresses from other sources.
Homology: judge whether the protocol, domain name [IP], and port are the same between two communication addresses.ajax: http://127.0.0.1/index.html
api data interface: http://localhost/indexAre these two homologous? Not homologous. Whether or not the same source is judged is not based on the computer, but on whether or not the string of protocol, domain name and port is used.
-
By default, ajax will be affected by the same source policy. Once affected, an error will be reported as follows:
No 'Access-Control-Allow-Origin' header is present on the requested resource -
To solve the problem that ajax can only access the data interface from the same source:
- CORS, cross domain resource sharing, is set in the response line of the server:
Access control allow origin: allowed domain name address - jsonp
- Server agent or not
Idea: request the corresponding server interface through python, after obtaining the data,
JSON method
- CORS, cross domain resource sharing, is set in the response line of the server:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jsonp</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> </head> <body> <button>click</button> <script> // function get_data(){ // //Send request // //1. Create a cross domain label [script] // var script = document.createElement("script"); // //2. Add the src attribute to the tag to point to the requested address // script.src= " http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query= My Chinese heart“ // console.log(script); // //3. Put the set script tag in the head tag // document.head.appendChild(script); // //4. Call the data returned by the server, declare a function in advance, and take the returned data as parameters // // } // // callback(`{"song":[{"bitrate_ Fee ":" {\ \ "0 \ \": \ "0|0 \ \", "1 \ \": \ "0|0 \ \"} "," weight ":" 13099 "," songname ":" my Chinese heart "," resource "_ type":"0","songid":"604603771","has_ mv":"0","yyr_ artist":"0","resource_ type_ ext":"0","artistname":"CBS","info":"","resource_ provider":"1","control":"0000000000","encrypted_ songid":"78082409857A085D08CADC"},{"bitrate_ Fee ":" {\ \ "0 \ \": \ "129|-1 \ \", "1 \ \": \ "- 1|-1 \ \"} "," weight ":" 4199 "," songname ":" the moon represents my Chinese heart "," resource "_ type":"0","songid":"544880401","has_ mv":"0","yyr_ artist":"0","resource_ type_ Ext ":" 2 "," artistname ":" Daqing Xiaofang "," info ":", "resource_ provider":"1","control":"0000000000","encrypted_ songid":"3408207A37080859645F87"}],"order":"song,album","error_ Code ": 22000," album ": [{" album ":" my Chinese heart "," weight ":" 130 "," artist name ":" CBS "," resource "_ type_ ext":"0","artistpic":"http:\/\/qukufile2. qianqian.com \/data2\/pic\/3b22a5976d07dbbe38b60f92ab2b6afd\/660129785\/660129785. jpg@s_ 2,w_ 40,h_ 40 "," album ":" 604603768 "}, {" album ":" my Chinese heart "," weight ":" 0 "," artist name ":" Chen Dongdong "," resource "_ type_ ext":"0","artistpic":"http:\/\/qukufile2. qianqian.com \/data2\/pic\/default_ album.jpg @s_ 2,w_ 40,h_ 40","albumid":"611655247"}]}`) // function callback(data){ // console.log(data); // } $.ajax({ url:"http://tingapi.ting.baidu .com/v1/restserver/ting?method= baidu.ting.search . catalogsug & Query = my Chinese heart ", type:"get", dataType:"jsonp" }).then(response=>{ console.log(response); }); </script> </body> </html>