VUE使用axios請求后端數據


引言

最近學習vue嘗試使用axios請求后端數據,發現了一大堆問題,后端接收不到請求的數據。查了資料之后,在這里總結記錄一下。

先說一下常用的幾種請求方式和模板:

Get方式

GET 方法傳遞參數格式如下:

<script type = "text/javascript">
  mounted () {
    axios.get('http://localhost:8022/user/login', {
    params: {
      ID: 12345	//參數ID
    }
  })
  .then(function (response) {	//請求成功
    console.log(response);
    alert(response.data.msg);
  })
  .catch(function (error) {		//請求失敗
    console.log(error);
  });
  }
})
</script>

Post方式

POST 方法傳遞參數格式如下:

<script type = "text/javascript">
  mounted () {
    axios.post('http://localhost:8022/user/login', {
    params: {
      ID: 12345	//參數ID
    }
  })
  .then(function (response) {	//請求成功
    console.log(response);
    alert(response.data.msg);
  })
  .catch(function (error) {		//請求失敗
    console.log(error);
  });
  }
})
</script>

axios API 方式

<script type = "text/javascript">
  mounted () {
    //  可以將請求方式、URL、請求/響應格式、請求頭等參數進行單獨配置
	axios({		//GET 請求遠程圖片
  		method:'get',
 		url:'http://bit.ly/2mTM3nY',
  		responseType:'stream'
	})
  	.then(function(response) {
  		response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
	});
  }
})
</script>

axios響應結構

axios請求的響應包含以下信息:

{
  // `data` 由服務器提供的響應
  data: {},

  // `status`  HTTP 狀態碼
  status: 200,

  // `statusText` 來自服務器響應的 HTTP 狀態信息
  statusText: "OK",

  // `headers` 服務器響應的頭
  headers: {},

  // `config` 是為請求提供的配置信息
  config: {}
}

使用 then 時,會接收下面這樣的響應:

axios.get("/user/12345")
  .then(function(response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

axios配置默認值

可以指定將被用在各個請求的配置默認值。

全局的 axios 默認值:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

post請求出現的錯誤

我們知道在做 post 請求的時候,我們的傳參是 data: {...} 或者直接 {...} 的形式傳遞的。

在使用時,axios會幫我們 轉換請求數據和響應數據 以及 自動轉換 JSON 數據

而在使用post方式請求時,會出現后端接收不到數據的現象

解決方案一

【用 URLSearchParams 傳遞參數】

let param = new URLSearchParams()
param.append('username', 'admin')
param.append('pwd', 'admin')
axios({
	method: 'post',
	url: '/api/lockServer/search',
	data: param
})

需要注意的是: URLSearchParams 不支持所有的瀏覽器,但是總體的支持情況還是 OK 的,所以優先推薦這種簡單直接的解決方案


解決方案二

【使用qs庫】

npm install qs --save

import Qs from 'qs'		//引入qs
let data = {
	"username": "admin",
	"pwd": "admin"
}

axios({
	headers: {
		'deviceCode': 'A95ZEF1-47B5-AC90BF3'
	},
	method: 'post',
	url: '/api/lockServer/search',
	data: Qs.stringify(data)	//使用qs將參數轉換為query參數
})

網上有很多方案說使用

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

但是我用的時候不需要,沒請求成功的可以試試


解決方案三

可以通過修改 transformRequest 來達到我們的目的

import Qs from 'qs'
axios({
	url: '/api/lockServer/search',
	method: 'post',
	transformRequest: [function (data) {
	    // 對 data 進行任意轉換處理
	    return Qs.stringify(data)
    }],
	headers: {
		'deviceCode': 'A95ZEF1-47B5-AC90BF3'
	},
	data: {
	    username: 'admin',
		pwd: 'admin'
	}
})

歡迎訪問個人博客:http://www.itle.info/


免責聲明!

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



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