npm install axios
let axios = require('axios');
var url = 'https://github.com/JamieChen-1230';
axios.get(url)
.then((res) => {
// resolved時執行
// axios回傳的內容為一個對象,對象包含: data / status / statusText / headers / config 等屬性
console.log(res.data);
})
.catch((error) => {
// rejected時執行
console.error(error);
})
.finally(() => {
console.log('不論失敗成功與否皆會執行');
});
let axios = require('axios');
const config = {
// 只有url為必填
url: 'JamieChen-1230',
// 大小寫皆可
method: 'get',
// 請求頭設置
headers: { 'Content-Type': 'application/json' },
// 添加在url前面,除非url為絕對路徑
baseURL: 'https://github.com/',
// 請求體 (適用於 PUT、POST、PATCH等)
// data: { name: 'test', title: 777 },
// URL參數(適用於GET)
// params: { ID: 123 },
// 限制傳送資料大小
// maxContentLength: 2000,
// 請求時間超過5000毫秒(5秒),請求會被中止
timeout: 5000,
// 伺服器回應的數據類型
// 選項: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 瀏覽器才有'blob',預設為'json'
responseType: 'json',
// 伺服器回應的編碼模式 預設'utf8'
responseEncoding: 'utf8',
};
axios.request(config)
.then((res) => {
// resolved時執行
// axios回傳的內容為一個對象,對象包含: data / status / statusText / headers / config 等屬性
console.dir(res.data, {'depth': null});
})
.catch((error) => {
// rejected時執行
console.error(error);
})
.finally(() => {
// 不論失敗成功與否皆會執行
console.log('不論失敗成功與否皆會執行');
});
let axios = require('axios');
function func1(){
return axios.get('https://github.com/JamieChen-1230');
}
function func2(){
return axios.get('https://github.com/JamieChen-1230');
}
axios.all([func1(), func2()])
.then(axios.spread(function(res1, res2){
// res是依照發出請求的順序對應,而不是請求響應的先後順序
// res1 => func1(), res2 => func2()
console.log(res1, res2);
}));
JavaScript