axios 使用 post 發送數據時,默認是直接把 json 放到請求體中提交到后端的。也就是說,我們的 Content-Type 變成了 application/json;charset=utf-8 ,這是axios默認的請求頭content-type類型。但是實際我們后端要求的 'Content-Type': 'application/x-www-form-urlencoded' 為多見,這就與我們不符合。所以很多同學會在這里犯錯誤,導致請求數據獲取不到。明明自己的請求地址和參數都對了卻得不到數據。
我們現在來說說post請求常見的數據格式(content-type)
- Content-Type: application/json : 請求體中的數據會以json字符串的形式發送到后端
- Content-Type: application/x-www-form-urlencoded:請求體中的數據會以普通表單形式(鍵值對)發送到后端
- Content-Type: multipart/form-data: 它會將請求體的數據處理為一條消息,以標簽為單元,用分隔符分開。既可以上傳鍵值對,也可以上傳文件。
1)application/x-www-form-urlencoded,我們前端該如何配置:
常見方法匯總:
a.【用 URLSearchParams 傳遞參數】代碼簡單,省事。 需要注意的是: URLSearchParams 不支持所有的瀏覽器,但是總體的支持情況還是 OK 的
let param = new URLSearchParams() param.append('username', 'admin') param.append('pwd', 'admin') axios({ method: 'post', url: '/api/lockServer/search', data: param })
b. 配置axios請求頭中的content-type為指定類型
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
或者
{headers:{'Content-Type':'application/x-www-form-urlencoded'}}
將參數轉換為query參數, 利用qs,引入 qs ,這個庫是 axios 里面包含的,不需要再下載了。
import Qs from 'qs' let data = { "username": "cc", "psd": "123456" } axios({ headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'post', url: '/api/lockServer/search', data: Qs.stringify(data) })
2) Content-Type: multipart/form-data
let params = new FormData() params.append('file', this.file) params.append('id', localStorage.getItem('userID')) params.append('userName', this.name) params.append('sex', this.sex) params.append('mobile', this.phone) params.append('email', this.email) params.append('qq', this.qq) params.append('weChat', this.WeChat) axios.post(URL, params, {headers: {'Content-Type': 'multipart/form-data'}}).then(res => { if (res.data.code === 0) { this.$router.go(-1) } }).catch(error => { alert('更新用戶數據失敗' + error) })
3) Content-Type: application/json
這種是axios默認的請求數據類型,我們只需將參數序列化json字符串進行傳遞即可,無需多余的配置。
原文 https://www.cnblogs.com/dreamcc/p/10752604.html
axios 中文文檔:http://www.axios-js.com/zh-cn/docs/