1、簡述
在Web開發(fā)過程中,少不了發(fā)起Http請(qǐng)求服務(wù)端的接口數(shù)據(jù),在不同的框架中使用了不同的Http請(qǐng)求方式,常用的請(qǐng)求有fetch、 ajax、 axios、XMLHttpRequest、request,以下樣例僅供參考。
2、Fetch
Fetch API 是一種 JavaScript API,是一種基于 Promise 的現(xiàn)代API,用于在網(wǎng)絡(luò)中發(fā)送和接收請(qǐng)求。具有一下特點(diǎn):
- 更簡潔的 API:只需要一個(gè)函數(shù)就可以完成網(wǎng)絡(luò)請(qǐng)求。
- 基于 Promise:支持更直觀的異步編程。
- 內(nèi)置 Request 和 Response 類:方便進(jìn)行請(qǐng)求和響應(yīng)的處理。
- 支持跨域請(qǐng)求:允許在不同域名之間進(jìn)行數(shù)據(jù)交互。
2.1 GET
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
console.log(data); // 處理返回的數(shù)據(jù)
})
.catch(error => {
console.error(error); // 處理錯(cuò)誤
});
2.2 POST
const data = new FormData();
data.append('name', '張');
data.append('age', 20);
fetch('https://example.com/submit', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: new URLSearchParams(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
3、Ajax
Ajax 全稱“Asynchronous JavaScript and XML”,譯為“異步 JavaScript 和 XML”,程序員們習(xí)慣稱之為“阿賈克斯”,它并不是一種技術(shù),而是多種技術(shù)的綜合體,其中包括 JavaScript、XML、JSON、DOM、CSS、HTML 以及最重要的 XMLHttpRequest 對(duì)象。通過 Ajax 可以異步從服務(wù)器請(qǐng)求數(shù)據(jù)并將數(shù)據(jù)更新到網(wǎng)頁中,整個(gè)過程不需要重載(刷新)整個(gè)網(wǎng)頁,可以將網(wǎng)頁的內(nèi)容更快的呈現(xiàn)給用戶。
3.1 GET
$.ajax({
url: "https://api.example.com/data",
type: 'GET',
dataType: 'json',
success: function (data) {
},
error: function () {
}
});
3.2 POST
let formData = new FormData();
formData.append('id', fileId);
$.ajax({
url:'https://example.com/submit',
type: 'POST',
processData: false,
contentType: false,
data: formData,
dataType: 'json',
success: function (data) {
},
error: function (e) {
}
});
3.3 Done
從JQuery 1.8,$.ajax()的 success() 被替換為 done() ,error() 被替換為 fail() ,complete() 被替換為 always() 。
$.ajax({
type: "POST",
url: "https://example.com/submit",
dataType: "json",
}).done(function(data){
console.log(data)
}).fail(function(jqXHR, textStatus, errorThrown){
}).always(function( jqXHR, textStatus ){
});
4、Axios
Axios是一個(gè)基于promise的HTTP庫,類似于jQuery的ajax,用于http請(qǐng)求。可以應(yīng)用于瀏覽器端和node.js,既可以用于客戶端,也可以用于node.js編寫的服務(wù)端。
- 支持Promise API
- 攔截請(qǐng)求與響應(yīng),比如:在請(qǐng)求前添加授權(quán)和響應(yīng)前做一些事情。
- 轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù),比如:進(jìn)行請(qǐng)求加密或者響應(yīng)數(shù)據(jù)加密。
- 取消請(qǐng)求
- 自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
- 客戶端支持防御XSRF
4.1 引用
常用的引入axios方法:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
或者通過node npm來安裝:
npm install axios
方法列舉:GET、POST、PUT、PATCH、DELETE
4.2 GET
let params= {};
params.id = 1;
axios({
method: "GET",
url: "https://api.example.com/data",
params:params
}).then(res => {
console.log(res);
});
或者
axios.get("https://api.example.com/data", {
params: params
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
4.3 POST
let formData = new FormData();
formData.append('id', fileId);
axios.post('https://example.com/submit',formData).then(res=>{
console.log(res,'formData')
})
5、XMLHttpRequest
XMLHTTPRequest對(duì)象,顧名思義:是基于XML的HTTP請(qǐng)求。XMLHTTPRequest是一個(gè)瀏覽器接口,使得Javascript可以進(jìn)行HTTP(S)通信。XMLHTTPRequest(XHR)對(duì)象用于與服務(wù)器交互,我們通過 XMLHttpRequest 可以在不刷新頁面的情況下請(qǐng)求特定 URL獲取數(shù)據(jù),并且雖然名字叫XMLHTTPRequest,但實(shí)際上可以用于獲取任何類型的數(shù)據(jù)。
5.1 GET
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.send();
xhr.onreadystatechange = function(){
if ( xhr.readyState == 4 && xhr.status == 200 ) {
alert( xhr.responseText );
} else {
alert( xhr.statusText );
}
};
5.2 POST
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://example.com/submit', true);
xhr.responseType = "blob";
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.onload = function () {
if (xhr.status == 200) {
var blob = new Blob([xhr.response], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream;charset=utf-8"'
})
var reader = new FileReader();
reader.onload = function () {
console.log(this.result);
};
reader.readAsArrayBuffer(blob);
}
};
xhr.send();
6、Request
Node.js是一個(gè)基于Chrome V8 JavaScript引擎的開源、跨平臺(tái)的Javascript運(yùn)行環(huán)境,使JavaScript可以脫離瀏覽器運(yùn)行。它提供了很多強(qiáng)大的模塊,使Web開發(fā)更輕松。其中,request模塊是一個(gè)使用最廣泛的HTTP模塊,可以用來發(fā)送HTTP/HTTPS請(qǐng)求。文章來源:http://www.zghlxwxcb.cn/news/detail-727991.html
添加request模塊:文章來源地址http://www.zghlxwxcb.cn/news/detail-727991.html
npm install request
6.1 GET
var request = require('request');
request.get('https://api.example.com/data', function(error, response, body) {
console.log(body);
});
6.2 POST
var request = require('request');
request.post('https://example.com/submit', {form:{key:'value'}}, function(error, response, body) {
//上傳文件或者其他操作
});
到了這里,關(guān)于Web:前端常用的幾種Http請(qǐng)求GET和POST樣例的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!