Summarize several network request methods that can be used in Vue

##1、XMLHttpRequest

The browser has insufficient support for the XMLHttpRequest object. When creating the XMLHttpRequest object, it needs to be compatible with the IE browser.
: XHR

  • readyState
    • 0-4, 0 means not initialized, 4 means the request has been completed
  • status (HTTP response status code)
    • 200: OK, success
    • 3XX【Redirection series status code】
      • 301: Permanent redirect
      • 302: Temporary redirect
      • 307: Internal browser (cache) redirection
    • 4XX【error series】
      • 400: bad request, bad request
      • 401: Authentication failed
      • 403: Forbidden
      • 404: Cannot find the corresponding resource
      • 405: Method not allowed
    • 5XX【Server error, environmental problem】
      • 500: Internal server error (code, environmental issues)
      • 502: bad Getway, bad gateway

Case: Use XHR to request the data interface of national colleges and universities

  • interface address

    • https://api.i-lynn.cn/college
    • Just display the listinformation in a loop
    • Interface can be directly requested across domains
  • Case effect

University data

Reference Code:

<body>
    <div id="app">
        <ul>
            <li :key='index' v-for='(el,index) in list'>{
   
   {el.area}}:{
   
   {el.counts}}所</li>
        </ul>
    </div>
</body>

<script src="./js/vue.js"></script>
<script>
    new Vue({
     
     
        el: '#app',
        data: {
     
     
            list: []
        },
        mounted: function(){
     
     
            // 1. 创建xhr对象
            var xhr = new XMLHttpRequest()
            const api = 'https://api.i-lynn.cn/college'
            // 2. 绑定回调函数
            xhr.onreadystatechange = () => {
     
     
                // 3. 判断是否成功
                if(xhr.readyState == 4 && xhr.status == 200){
     
     
                    this.list = JSON.parse(xhr.responseText).list
                }
            }
            // 4. 打开请求
            xhr.open('GET',api)
            // xhr.open('POST',api)
            // 设置请求头
            // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            // 5. 发送请求
            xhr.send()
            // xhr.send("username=111&age=222")
        }
    })
</script>

2、jQuery

The introduction of the jQuery class solves the trouble of writing compatibility, but now it only uses the network request function in the jQuery library, and a large number of dom methods in jQuery are introduced invalid, which is a bit of overkill.

Basic grammar

$.ajax({
    
    
	url,
	type:get/post,
	data,
	dataType:json/text/xml/html/jsonp
	success:function(res){
    
    },
	error:function(){
    
    }
})

$.get(url,data,callback,dataType)

$.post(url,data,callback,dataType)

Rewrite XHRpart of the case using jQuery

<body>
    <div id="app">
        <ul>
            <li :key="index" v-for="(el,index) in list">
                {
   
   {el.area}}:{
   
   {el.counts}}所
            </li>
        </ul>
    </div>
</body>

<script src="./js/vue.js"></script>
<script src="./js/jquery-3.5.1.js"></script>
<script type="text/javascript">
    const vm = new Vue({
     
     
        el: "#app",
        data: {
     
     
            list: [],
        },
        async mounted() {
     
     
            const api = "https://api.i-lynn.cn/college";
            let data = await $.get(api,"json");
            this.list = data.list;
        },
    });
</script>

async: keyword, used to functionmark the current function as an asynchronous function before the function declaration keyword

await: keyword, let the line code of the current keyword execute and wait until the result is reached before executing the subsequent code

3、fetch

  • Built-in API provided by HTML5

  • Simpler data acquisition method, more powerful and flexible, can be regarded as an upgraded version of xhr

  • Based on Promise

  • Fetch supports many request methods, but the default is GETrequest. If you need to use other methods, you can methodspecify it through the option of the second optional parameter

Grammatical structures

fetch(url[,some settings]).then(fn2)
		  .then(fn3)
		  ...
          .catch(fn)

Usage example

// 通过url表达式来传递数据
fetch("http://xxx/?id=123")
    .then(res => res.json())
    .then(data => console.log(data));

// post标准提交
fetch("http://xxxx/post", {
    
    
    method: "post",
    body: "uname=lisi&pwd=123",
    headers: {
    
    
        "Content-Type": "application/x-www-form-urlencoded",
    },
	})
    .then(res => res.json())
    .then(data => console.log(data));

// post提交json数据
fetch("http://localhost:3000/books", {
    
    
    method: "post",
    body: JSON.stringify({
    
    
        uname: "tianqin",
        pwd: "1201",
    }),
    headers: {
    
    
        "Content-Type": "application/json",
    },
	})
    .then(res => res.json())
    .then(data => console.log(data));

Note: fetch will not send cookies. Unless you use the initialization option of credentialscredentials: "include"

In the above code example, we will see that there is a json()method, which is the response result processing method of fetch. The commonly used response result processing methods of fetch are:

  • text(): Process the returned body into a string type
  • json(): The returned result is the same as JSON.parse(responseText)

Use the fetch method to rewrite XHRsome cases

<body>
    <div id="app">
        <ul>
            <li :key='index' v-for='(el,index) in list'>
                {
   
   {el.area}}:{
   
   {el.counts}}所
            </li>
        </ul>
    </div>
</body>

<script src="./js/vue.js"></script>
<script type="text/javascript">
    const vm = new Vue({
     
     
        el: '#app',
        data: {
     
     
            list: []
        },
        async mounted() {
     
     
            const api = "https://api.i-lynn.cn/college"
            let res = await fetch(api)
            let data = await res.json()
            this.list = data.list
        }
    })
</script>

Preflight request

When the asynchronous request is a non-traditional GETAND POST, the browser will first send a request to the interface address to ask whether the current server supports the request type (request verb), if it does, it will continue to send the asynchronous request, otherwise it will not be sent .

Then this pre-sent request is called 预检请求, its request verb is OPTIONS.

The latter part of learning PUT, DELETEand other special requests will trigger verb preflight request.

Preflight request verb

4、axios

###4.1、Basic usage

Document: https://www.kancloud.cn/yunye/axios/234845

axios is a promise-based HTTP library that can be used in browsers and node.js. axios is a network request library recommended by the author of vue . It has the following characteristics:

  • Support browser and node.js
  • Support promise
  • Able to intercept请求和响应
  • Automatically convert json data

axios browser support

axios compatibility

Before using axios, you need to introduce the axios js library file in the corresponding template file, and then use axios according to the following usage:

// GET请求方式
axios.get('/get_data?id=10010').then(ret => console.log(ret.data))

axios.get('/get_data',{
    
    
    params: {
    
    
        id: 10010,
        name: 'tianqin',
        age: 21
    }
}).then(ret => console.log(ret.data))

//POST请求方式
axios.post('/set_data', {
    
    
  	firstName: 'zhang',
  	lastName: 'san'
}).then(ret => {
    
     })

axios({
    
    
  	method: 'post',
  	url: 'set_data',
  	timeout: 1000,
  	headers: {
    
    'X-Custom-Header': 'foobar'},
  	data: {
    
    
    	firstName: 'tian',
    	lastName: 'qin'
  	}
}).then(ret => {
    
     })

Of course axios In addition to supporting traditional GETand POSTway beyond , way also supports common request:

  • put: modify data
  • delete: delete data

Take the axios request example above as an example, retthe main attributes of the axios response result ( ) are:

  • data: the actual response data (most commonly used)
  • headers: response header information
  • status: response status code
  • statusText: response status information

In addition, it should be noted that before using axios to send a request, it allows us to make some settings through global configuration , which can facilitate subsequent request operations, for example:

  • axios.defaults.timeout = 3000【Set timeout time】
  • axios.defaults.baseURL ='http://localhost/app' [Set the default address]
  • axios.defaults.headers['_token'] = '123123123'[Set request header information, general header information]
    • axios.defaults.headers.get[’_token’] = ‘123123’
    • axios.defaults.headers.post[’_token’] = ‘123123’
    • axios.defaults.headers.common['_token'] = '123123'[Common header information, common can not be written]

note:

  • When axios sends a post request, it sends json format data by default
  • If you need to send a post form request, you need to specify the request header
axios.post('college',{
     
     
    username: 'tianqin',
    age: 21
},{
     
     
    headers: {
     
     
        "Content-Type": "application/x-www-form-urlencoded"
    }
}).then(ret => this.list = ret.data.list)

Use axios to rewrite XHRsome cases

<!-- 以GET形式为例 -->
<body>
    <div id="app">
        <ul>
            <li :key='index' v-for='(el,index) in list'>
                {
   
   {el.area}}:{
   
   {el.counts}}所
            </li>
        </ul>
    </div>
</body>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/vue.js"></script>
<script type="text/javascript">
    const vm = new Vue({
     
     
        el: '#app',
        data: {
     
     
            list: []
        },
        mounted() {
     
     
            const api = "https://api.i-lynn.cn/college"
            axios.get(api).then(ret => console.log(ret.data.list))
        }
    })
</script>

Guess you like

Origin blog.csdn.net/qq_43377853/article/details/109060284