vue中axios的post請求,415錯誤的問題
vue axios的post請求415錯誤
415錯誤
415是HTTP協(xié)議的狀態(tài)碼415的含義是不支持的媒體類型(Unsupported media type)檢查是否在POST請求中加入了headerheader中是否包含了正確的Content-Type
需求分析
需求:請求本地平臺上數(shù)據(jù)庫的表單數(shù)據(jù)
問題:請求415錯誤
原因:請求格式頭問題

我想請求的是表單數(shù)據(jù),但是一直默認(rèn)是請求json數(shù)據(jù),因為沒有后端的原因,需要前端解決。
方法:
axios({
method: 'post',
url: 'http://localhost:8080/jsaas_war/restApi/sys/queryForJson?alias=three¶ms',
data: JSON.stringify(),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
//下面這段代碼
transformRequest: [function (data) {
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}],
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
其中發(fā)揮關(guān)鍵作用的是headers與transformRequest。其中 headers 是設(shè)置即將被發(fā)送的自定義請求頭。
transformRequest 允許在向服務(wù)器發(fā)送前,修改請求數(shù)據(jù)。
這樣操作之后,后臺querystring.parse(decodeURIComponent(data))獲取到的就是類似于{ name: ‘w’, password: ‘w’ }的對象。
另外一種辦法就是后端去改,本文就不作具體解釋了。。。
vue-axios的get、post請求

- 直接在控制臺上打印axios會報錯,打印fetch就不會;
- 因為fetch是標(biāo)準(zhǔn),axios是第三方,要想用axios,就必須引入想應(yīng)的js文件;
- axios-js文件下載:npm
- 搜索axios,點進(jìn)去,往下找:

- 打開鏈接:“https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js”,ctrl+s保存源碼,就下載好了;
- 然后引入到html中就可以使用了。
get方式:axios請求數(shù)據(jù)核心代碼
axios.get("./test.json").then(res => {
console.log(res)
//數(shù)據(jù)在res.data.data.films里
console.log(res.data.data.films)
})完整代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../lib/vue.js"></script>
<script src="axios.min.js"></script>
</head>
<body>
<div id="box">
<button @click="handleClick">axios</button>
</div>
<script>
new Vue({
el:"#box",
data:{
},
methods:{
handleClick(){
axios.get("./test.json").then(res => {
console.log(res)
//數(shù)據(jù)在res.data.data.films里
console.log(res.data.data.films)
})
}
}
})
</script>
</body>
</html>結(jié)果:

post方式:不用寫headers
攜帶的信息放在第二個參數(shù)位置上就可以了,不用寫其他的;
handleClick(){
axios.post("./test.json","name=yiyi&age=100").then(res => {
console.log(res)
//數(shù)據(jù)在res.data.data.films里
console.log(res.data.data.films)
})
}axios.post("./test.json",{name:"yiyi",age:100})axios請求數(shù)據(jù)的方式比fetch方式更簡單,直接一個then就可以;
而且post方式還不用寫headers,直接寫數(shù)據(jù),會自動查看你攜帶的數(shù)據(jù)是什么類型;
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue.js 通過jQuery ajax獲取數(shù)據(jù)實現(xiàn)更新后重新渲染頁面的方法
今天小編小編就為大家分享一篇Vue.js 通過jQuery ajax獲取數(shù)據(jù)實現(xiàn)更新后重新渲染頁面的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08
vue3通過render函數(shù)實現(xiàn)菜單下拉框的示例
本文主要介紹了vue3通過render函數(shù)實現(xiàn)菜單下拉框的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
vue3中<script?setup>?和?setup函數(shù)的區(qū)別對比
這篇文章主要介紹了vue3中<script?setup>?和?setup函數(shù)的區(qū)別,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04

