十五推沸、axios的使用
1.安裝axios組件
cnpm install axios -s //先在項(xiàng)目安裝axios這個(gè)組件
cnpm install //安裝一下axios需要的其他插件
2.在main.js加入axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vus.use(VueAxios,axios)
3.發(fā)送ajax請(qǐng)求
//get,參數(shù)放到url后面
this.axios({
method:"get",
url:"http://url?name="+name+"&title="+title
}).then((response)=>{
console.log(response);
});
//post,參數(shù)加入data中
this.axios({
method:"post",
url:"http://url",
data:{
name:name,
title:title
}
}).then((response)=>{
console.log(response);
});
4.axios注意點(diǎn)
前端向后端傳輸數(shù)據(jù)時(shí)券坞,如果是get傳輸鬓催,直接傳在url后;如果是post傳輸恨锚,則在請(qǐng)求體body中傳輸宇驾。
在body中的數(shù)據(jù)格式又有兩種,一種是 json 數(shù)據(jù)格式猴伶,另一種是 字符串课舍。具體要用哪種格式取決于后端入?yún)⒌母袷健?/p>
如果后端接收json數(shù)據(jù)類型,post 的 headers 需要設(shè)置 { ‘content-type’: ’application/json’ }他挎,傳給后端的數(shù)據(jù)就形如 { ‘name’:’edward’, ‘a(chǎn)ge’:’25’ }
如果后端接收的是(表單)字符串類型筝尾,post 的 headers 需設(shè)置 { ‘content-type’: ’application/x-www-form-urlencoded’ },
办桨,傳輸給后端的數(shù)據(jù)就形如 ‘name=edward&age=25’
如果想改變axios的post請(qǐng)求筹淫,帶參協(xié)議有兩種方式