This is the 18th day of my participation in the August Challenge
Life is too short to learn Python together
Vue implements data requests through AXIos
Vue.js does not provide Ajax functionality by default.
So when using VUE, it is common to use axiOS plug-ins to implement ajax data interaction with back-end servers.
Note that AXIos is essentially an Ajax wrapper around javascript, so it is restricted by the same origin policy.
- Axios download address
unpkg.com/[email protected]…. unpkg.com/[email protected]….
- Using document
www.kancloud.cn/yunye/axios…
Axios provides two common methods for sending HTTP requests :axios.get() and axios.post().
- Send a GET request
/ / parameter 1: Mandatory, string, url of the requested data interface, for example, request address: http://www.baidu.com?id=200 // parameter 2: Get (' server resource address ',{// http://www.baidu.com params:{parameter name :' parameter value ', // id: If (response=>{console.log(" request successful "); if (response=>{console.log(" request successful "); console.log(response.data); }). Catch (error=>{console.log(" request failed "); console.log(error.response); // Get error message}); // Get request case -- view city weather<script>
var vm = new Vue({
el:'#app'.data:{
},
// Automatically send Ajax to fetch data when initialization is complete
created(){
axios.get('http://wthrcdn.etouch.cn/weather_mini?city= Beijing',).then(response= >{
// The request succeeded
console.log(response);
console.log(response.data)
}).catch(error= >{
// The request failed or a bug appeared in the then code
console.log('Error reported');
// Get the error object
console.log(error);
// Get error information about the server
// console.log(error.response.data);})}})</script>
Copy the code
- Send a POST request
/ sends a POST request with parameters and uses similar to axios.get(). / / parameter 1: Mandatory, string, URL of the requested data interface // Parameter 2: mandatory, JSON object, parameter to be supplied to the data interface, if there are no parameters, then {} // parameter 3 must be used: Optional, JSON object, request header information axios.post(' server resource address ',{username: 'xiaoming', password: '123456'},{headers:{option name :" option value ",}}). }). Catch (error=>{console.log(error); }); // b'firstName=Fred&lastName=Flintstone'Copy the code
- Pay attention to
Add POST Delete Delete Change PUT /patch Query GET
Axios.delete () has the same usage and arguments as axios.get(),
Axios.put () or axios.patch has the same usage and arguments as axios.post().
In HTTP, different request actions have different meanings. For example:
Get represents a request to the target server for data
Post represents a request to the target server to upload data
Put stands for asking the target server to update data.
Patch represents to request the target server to update data [modify some data]
Delete represents a request to the target server to delete data
json
Json is an acronym for JavaScript Object Notation. The word stands for JavaScript Object Notation, a data format that is similar to JavaScript objects.
What JSON does: Transfer data between different system platforms, or between different programming languages.
- Syntax for JSON data
Json data objects are similar to objects in JavaScript, but there is no function method in the value corresponding to the key. The value can be ordinary variables, undefined is not supported, and the value can also be an array or JSON object.
// A native JS json object
var obj = {
age:10, sex: 'female ', work(){// work: function(){
return "Study hard.",}}Json data format, there are no methods, only properties, property values: string, value (integer, floating point, Boolean), json,
{
"name":"tom"."age":18
}
// Json data array format:
["tom".18."programmer"]
Copy the code
- Complex JSON-formatted data can include object and array writing.
{
"name":"Xiao Ming"."age":200."is_delete": false."fav": ["code"."eat"."swim"."read"]."son": {"name":"Xiao Xiao Ming"."age":100."lve": ["code"."eat"]}}// Array structures can also be used as JSON to transfer data.
Copy the code
Json data can be stored in a. Json file, which usually contains only one JSON object.
- conclusion
- The extension of the JSON file is. Json
- Json files typically hold a single JSON data
- Json data attributes cannot be methods or undefined, and can only be: numeric [integer, decimal, Boolean], string, JSON, and array
- Json data is only quoted, each attribute member is separated by a comma, and the last member is not comma. {” name “:” Ming “, “age” : 200, “fav:” [” code “, “eat”, “swim”, “read”], “son” : {” name “:” small xiao Ming “, “age” : 100}}
- Json data conversion method provided by js
Javascript provides a JSON object to manipulate data conversion of JSON data.
methods | parameter | The return value | describe |
---|---|---|---|
stringify | Json object | string | Json objects are converted to strings |
parse | string | Json object | Json data in string format is converted into JSON objects |
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/ / json syntax
let humen = {
"username":"xiaohui"."password":"1234567"."age":20
};
console.log(humen);
console.log(typeof humen);
JSON object provides JSON format data conversion function
// stringify(json object) # convert JSON to a string
let result = JSON.stringify(humen);
console.log(result);
console.log(typeof result);
// Parse (string type JSON data) # Convert strings into JSON objects
let json_str = '{"password":"1123","age":20,"name":"xiaobai"}';
console.log(json_str)
console.log(typeof json_str)
let json_obj = JSON.parse(json_str);
console.log(json_obj);
console.log(typeof json_obj)
console.log(json_obj.age)
</script>
</body>
</html>
Copy the code
ajax
Ajax, commonly known as “Ajax” in Chinese, is a short form of English “Async Javascript And Xml”, translated as: asynchronous JS And Xml data transfer data.
Ajax functions: Ajax can make JS instead of the browser to send HTTP requests to the back end of the program, communicate with the back end, in the case of users do not know the operation of data and information, so as to achieve page local refresh data/no refresh update data.
Therefore, Ajax is a very common technology in Web development, mainly used to operate the data interface provided by the back end, so as to achieve 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 methods provided by this object to communicate data with the back end.
In fact, Ajax, provided by Axios or jQuery, is essentially a wrapper around the actions of the XMLHttpRequest object.
Data interface
Data interface, also called API interface, indicates that the back end provides the URL address to manipulate data/function for the client to use.
The client initiates a request to apply for operation data from the URL provided by the server.
Also at work, most of the data interfaces are not written by hand, but are generated through function libraries/frameworks.
The use of ajax
Ajax must be used in conjunction with the server program, but for now we will learn how to use Ajax, so we won’t get into the server-side Python code for now. Therefore, we can make calls using data interfaces written by others.
JQuery wraps Ajax into a function $.ajax() that you can use to execute ajax requests directly.
interface | address |
---|---|
The interface | WTHRCDN. Etouch. Cn/weather_min… |
Music Interface Search | Tingapi.ting.baidu.com/v1/restserv… |
Music message interface | Tingapi.ting.baidu.com/v1/restserv… |
Write code to get the data provided by the interface:
JQ version
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="Js/jquery - 1.12.4. Js"></script>
<script>
$(function(){$("#btn").on("click".function(){
$.ajax({
// The url of the backend program
url: 'http://wthrcdn.etouch.cn/weather_mini'.// You can also use method to submit data. The default is 'GET' and 'POST'.
type: 'get'.dataType: 'json'.// Return data in 'json',' HTML ',' jsonp '
data: {// Set the data sent to the server. If it is a GET request, it can also be written to the URL. behind
"city":'Beijing'
}
})
.done(function(resp) { // The operation after the request succeeds
console.log(resp);
})
.fail(function(error) { // The operation after the request failed
console.log(error);
});
});
})
</script>
</head>
<body>
<button id="btn">Click to get data</button>
</body>
</html>
Copy the code
Vue version:
<! DOCTYPEhtml>
<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">
<input type="text" v-model="city">
<button @click="get_weather">Click to get the weather</button>
</div>
<script>
let vm = new Vue({
el:"#app".data: {city:"",},methods: {get_weather(){
/ / http://wthrcdn.etouch.cn/weather_mini?city= city name
axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
.then(response= >{
console.log(response);
}).catch(error= >{
console.log(error.response)
});
// The above parameter can also be written in the following format:
// axios.get("http://wthrcdn.etouch.cn/weather_mini",{
// // Parameters attached to the get request
// params:{
// "city":" city",
/ /}
// }).then(response=>{
// console.log(response.data); // Get interface data
// }).catch(error=>{
// console.log(error.response); // Get an error message
// })}}})</script>
</body>
</html>
Copy the code
The same-origin policy
The same origin policy is a security mechanism used by browsers to protect user information security. Same-origin refers to whether the protocol, domain name (IP), and port are the same between two addresses for communication (for example, the server interface address and the browser client page address). Client-side scripts [javascript] from different sources are rejected by the browser to display server-side information to the front-end Ajax without explicit authorization from the server.
Ajax is essentially javascript, a scripting language that runs in the browser, and so is limited by the browser’s same-origin policy.
Front-end address:http://www.test.cn/index.html |
Whether the same | why |
---|---|---|
http://www.test.cn/user/login.html |
is | The protocol, domain name, and port are the same |
http://www.test.cn/about.html |
is | The protocol, domain name, and port are the same |
https://www.test.cn:443/user/login.html |
no | Different protocols (HTTPS and HTTP) |
http:/www.test.cn:5000/user/login.html |
no | Different ports (5000 and 80) |
http://bbs.test.cn/user/login.html |
no | Different domain names (BBS and WWW) |
Same origin policy for Ajax interception, code:
<! DOCTYPEhtml>
<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">
<input type="text" v-model="music"><button @click="get_music">Query song</button>
</div>
<script>
var vm = new Vue({
el:"#app".data: {music:"".// Song title
},
methods: {get_music(){
axios.get(`http://tingapi.ting.baidu.com/v1/restserver/ting`, {params: {method:"baidu.ting.search.catalogSug".query:this.music,
}
}).then(response= >{
console.log("Data query successful!");
}).catch(error= >{
console.log("Query data failed!"); }}}})</script>
</body>
</html>
Copy the code
The above code runs incorrectly as follows:
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.
Copy the code
Access-control-allow-origin = access-Control-allow-origin
Whenever this keyword appears, access is restricted. The same origin policy interception problem occurred. Procedure
CORS for Ajax cross-domain (cross-source) solutions
Ajax cross-domain (cross-source) solutions: Server-side authorization [CORS], JSONP, server-side proxy
CORS, which stands for "Cross-domain Resource Sharing," is a W3C standard that allows browsers to make Ajax requests to back-end servers across sources, overcoming the limitation that Ajax can only be used in the same source. The realization of CORS mainly depends on setting the response header information to return </mark> in the response data of the <mark> backend server.Copy the code
Django views [pseudocode]
def post(request):
response = new Response()
response.set_header("Access-Control-AllowOrigin","http://localhost:63342")
return response;
Copy the code
Access-control-allow-origin: access-control-allow-origin: access-control-allow-origin: www.test.cn # indicates that ajax can only be accessed by clients of www.test.cn domain names. // * Indicates that Ajax can be accessed by clients of any source. Access-control-allow-origin: * Indicates that AJAX can be accessed by clients of any sourceCopy the code
conclusion
0. Same-origin policy: a security mechanism of the browser to protect user data. Browsers restrict Ajax from accessing data addresses from other sources across the source. Same-origin: Checks whether two communication addresses are consistent in protocol, domain name [IP], and port. Ajax: http://127.0.0.1/index.html API data interface: http://localhost/index is the two homologous? It's not homologous. The same origin is determined not by the computer, but by the string of protocol, domain name, and port. No 'access-Control-allow-origin' header is present on the requested resource 2. 1. CORS, cross-domain resource sharing, set access-Control-allow-origin in the server response line: access-Control-allow-origin Jsonp is not Ajax technology in nature. The core implementation of JSONP relies on script itself to load external JS files to achieve. Jsonp, of course, also needs the cooperation of the server. 3. Whether the server proxy idea: Through Python to request the corresponding server interface, the client and Python side are in the same origin, so the server proxy is realizedCopy the code
conclusion
The article was first published in the wechat public account Program Yuan Xiaozhuang, at the same time in nuggets.
The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)