axios基本使用


axios相關使用

一、axios安裝

  • 使用npm安裝axios
	npm install axios
  • 使用cnpm安裝axios
	cnpm install axios
  • 使用yarn安裝axios
	yarn install axios
  • 使用cdn鏈接axios
	<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

二、請求數據方法

  • get請求:方式一:
	axios({
		// 默認請求方式為get
		method: 'get',
		url: 'api',
		// 傳遞參數
		params: {
			key: value
		},
		// 設置請求頭信息
		headers: {
			key: value
		}
		responseType: 'json'
	}).then(response => {
		// 請求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 請求失敗,
		console.log(error);
	});
  • get請求:方式二
	axios.get("api", {
		// 傳遞參數
		params: {
			key: value
		},
		// 設置請求頭信息,可以傳遞空值
		headers: {
			key: value
		}
	}).then(response => {
		// 請求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 請求失敗,
		console.log(error);
	});
  • post請求:方式一
	// 注:post請求方法有的要求參數格式為formdata格式,此時需要借助 Qs.stringify()方法將對象轉換為字符串
	let obj = qs.stringify({
		key: value
	});
	
	axios({
		method: 'post',
		url: 'api',
		// 傳遞參數
		data: obj,
		// 設置請求頭信息
		headers: {
			key: value
		}
		responseType: 'json'
	}).then(response => {
		// 請求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 請求失敗,
		console.log(error);
	});
  • post請求:方式二
	let data = {
			key: value
		},
		headers = {
			USERID: "",
			TOKEN: ""
		};
	// 若無headers信息時,可傳空對象占用參數位置
	axios.post("api", qs.stringify(data), {
		headers
	}
	}).then(response => {
		// 請求成功
		let res = response.data;
		console.log(res);
	}).catch(error => {
		// 請求失敗,
		console.log(error);
	});
  • Qs的使用
    • 引用cdn或者使用npmcnpm或者yarn進行插件安裝
    • 使用cdn時,默認全局變量為Qs
    • Qs基本方法使用
      • qs.stringify() 方法:將目標數據轉換為string字符串
      • qs.parse() 方法:將對象字符串格式的數據轉換為對象格式


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM