JavaScript: fetch, realize asynchronous request

JavaScript: fetch(), realize asynchronous request

Fetch is a method of HTTP data request and an alternative to XMLHttpRequest. Fetch is not a further encapsulation of ajax, but native js. The Fetch function is native js and does not use the XMLHttpRequest object.

fetch

  • parameter

    1. URL: request address
    2. option: configuration options, using setting methods, request headers, request body, etc.;
  • demonstration

    fetch(URL,{
          
          
        method : 'POST',
        body : data,
        headers : {
          
          
            "ContentType" : "application/json"
        }
        // 其他配置
    })
        .then(response=>response.json())	//返回一个promise对象
        .then(data=>console.log(data))
        .catch(error=>console.log(error))
    
  • Advanced version

  • You can also new a Request object, and then pass in the fetch method after configuration

    let req = new Request(URL,{
          
          method : 'POST'});
    fetch(req)
        .then(response=>response.json())
    	.then(data=>console.log(data));	
    

Guess you like

Origin blog.csdn.net/yivisir/article/details/108000805