JS调用接口详解

发布时间:2023-05-19

JS调用接口的方法及注意事项

在前端开发中,经常需要通过JS调用API接口获取数据或与后端进行交互。本文将从多个方面详细介绍JS调用接口的方法及注意事项。

一、JS调用接口的方法

JS调用接口的方法有多种,如使用XMLHttpRequest对象、Fetch API、jQuery的$.ajax()、Vue.js的axios等。这里以使用XMLHttpRequest对象为例。

function postData() {  
    var url = "https://example.com/api";  
    var data = {name: 'John', age: 25};  
    var xhr = new XMLHttpRequest();  
    xhr.open("POST", url, true);  
    xhr.setRequestHeader("Content-Type", "application/json");  
    xhr.send(JSON.stringify(data));  
    xhr.onreadystatechange = function() {  
        if(xhr.readyState == 4 && xhr.status == 200) {  
            console.log(xhr.responseText);  
        }  
    }  
}  
postData();

上述代码使用XMLHttpRequest对象向指定URL发送POST请求,并将请求体数据转为JSON格式发送给后端。接收到响应后,在控制台中输出响应内容。

二、JS调用接口是如何更改Content-Type

发送POST请求时需要在Request Header中设置Content-Type,常见的Content-Type有以下几种:

  • application/x-www-form-urlencoded:表单数据
  • multipart/form-data:文件上传
  • application/json:JSON数据
    可以通过调用setRequestHeader方法设置Content-Type。例如:
var xhr = new XMLHttpRequest();  
xhr.open("POST", url, true);  
xhr.setRequestHeader("Content-Type", "application/json");  

上述代码将Content-Type设置为application/json

三、JS调用接口并发

JS可以通过创建多个XMLHttpRequest对象并同时发送请求实现并发。例如:

var xhr1 = new XMLHttpRequest();  
xhr1.open("GET", "https://example.com/api1", true);  
xhr1.send();  
var xhr2 = new XMLHttpRequest();  
xhr2.open("GET", "https://example.com/api2", true);  
xhr2.send();  
//在两个请求均获得响应后执行其他操作

上述代码中,同时发送了两个GET请求,并在两个请求均获得响应后执行其他操作。

四、JS调用接口获取返回

JS获取接口返回可以通过监听XMLHttpRequest对象的readystatechange事件,在响应状态为4(完成)且状态码为200时获取响应内容。例如:

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://example.com/api", true);  
xhr.send();  
xhr.onreadystatechange = function() {  
    if(xhr.readyState == 4 && xhr.status == 200) {  
        console.log(xhr.responseText);  
    }  
}  

上述代码中,监听XMLHttpRequest对象的readystatechange事件,当状态为4(完成)且状态码为200时,在控制台中输出响应内容。

五、JS调用接口设置超时时间

JS设置接口超时时间可以通过XMLHttpRequest对象的timeout属性实现。例如:

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://example.com/api", true);  
xhr.timeout = 5000; //设置超时时间为5秒  
xhr.send();  
xhr.onreadystatechange = function() {  
    if(xhr.readyState == 4 && xhr.status == 200) {  
        console.log(xhr.responseText);  
    }  
}  
xhr.ontimeout = function() {  
    console.log("请求超时!");  
}  

上述代码中,设置XMLHttpRequest对象的timeout属性为5000毫秒,监听ontimeout事件,当请求超时时在控制台中输出提示信息。

六、JS调用接口附件不下载

在下载附件时,服务器默认会将附件下载到本地。可以通过设置Content-Disposition响应头实现让浏览器在新标签页中打开附件而不是下载。例如:

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://example.com/api", true);  
xhr.responseType = "blob"; //设置响应类型为Blob  
xhr.setRequestHeader("Content-Disposition", "inline"); //设置Content-Disposition响应头  
xhr.send();  
xhr.onreadystatechange = function() {  
    if(xhr.readyState == 4 && xhr.status == 200) {  
        var url = URL.createObjectURL(xhr.response);  
        window.open(url); //在新标签页中打开Blob数据  
    }  
}  

上述代码中,设置XMLHttpRequest对象的responseType属性为blob,以获取Blob数据。同时设置Content-Disposition响应头为inline,实现浏览器在新标签页中打开附件而不是下载。在获取到Blob数据后,使用URL.createObjectURL方法生成URL,再通过window.open方法在新标签页中打开。

七、JS调用接口提示500

服务器返回500错误时,可以使用XMLHttpRequest对象的onerror事件监听错误,并在控制台中输出相应提示信息。例如:

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://example.com/api", true);  
xhr.send();  
xhr.onreadystatechange = function() {  
    if(xhr.readyState == 4 && xhr.status == 200) {  
        console.log(xhr.responseText);  
    }  
}  
xhr.onerror = function() {  
    console.log("服务器返回500错误!");  
}  

上述代码中,监听XMLHttpRequest对象的onerror事件,当服务器返回500错误时在控制台中输出提示信息。

八、JS调用接口前端超时请求链会断吗

前端发送请求后,如果在请求超时时未收到响应,请求链并不会断掉,仍然会发送到服务器。只是请求超时后监听到ontimeout事件并进行相应处理。

九、JS调用HTTP接口

JS调用HTTP接口可以使用XMLHttpRequest对象。例如:

var xhr = new XMLHttpRequest();  
xhr.open("GET", "http://example.com/api", true); //使用HTTP协议  
xhr.send();  
xhr.onreadystatechange = function() {  
    if(xhr.readyState == 4 && xhr.status == 200) {  
        console.log(xhr.responseText);  
    }  
}  

上述代码中,使用XMLHttpRequest对象通过HTTP协议向URL发送GET请求,并在接收到响应后在控制台中输出响应内容。

十、JS如何调用API接口数据

JS可以通过调用API接口获取数据,以JSON格式返回数据。例如:

var url = "https://example.com/api";  
fetch(url)  
    .then(function(response) {  
        return response.json();  
    })  
    .then(function(json) {  
        console.log(json);  
    });  

上述代码中,调用fetch方法获取URL返回的数据,通过链式调用then方法处理响应。第一个then方法将响应转为JSON格式,第二个then方法接收JSON数据并在控制台中输出。

结语

通过本文的详细介绍,相信大家对JS调用接口有了更深入的了解。在应用中,仍需根据具体情况进行调整和优化,充分发挥JS调用接口的作用。