Axios?get?post請求傳遞參數的實現(xiàn)代碼
Axios概述
首先,axios是基于promise用于瀏覽器和node.js的http客戶端
特點 :
支持瀏覽器和node.js
支持promise
能攔截請求和響應
能轉換請求和響應數據
能取消請求
自動轉換json數據
瀏覽器端支持防止CSRF(跨站請求偽造)
一、 安裝
npm安裝
$ npm install axios
bower安裝
$ bower install axios
通過cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
首先需要安裝axios
下一步,在main.js中引入axios
import axios from "axios";
與很多第三方模塊不同的是,axios不能使用use方法,由于axios比vue出來的早 所以需要放到vue的原型對象中
Vue.prototype.$axios = axios;
接著,我們就可以在App.vue中使用axios了
created:function(){
this.$axios.get("/seller",{"id":123}).then(res=>{
console.log(res.data);
});
}
1.發(fā)起一個get請求
<input id="get01Id" type="button" value="get01"/>
<script>
$("#get01Id").click(function () {
axios.get('http://localhost:8080/user/findById?id=1')
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
})
})
</script>另外一種形式:
<input id="get02Id" type="button" value="get02"/>
<script>
$("#get02Id").click(function () {
axios.get('http://localhost:8080/user/findById', {
params: {
id: 1
}
})
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
})
})
</script>2.發(fā)起一個post請求
在官方文檔上面是這樣的:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});但是如果這么寫,會導致后端接收不到數據
所以當我們使用post請求的時候,傳遞參數要這么寫:
<input id="post01Id" type="button" value="post01"/>
<script>
$("#post01Id").click(function () {
var params = new URLSearchParams();
params.append('username', 'sertyu');
params.append('password', 'dfghjd');
axios.post('http://localhost:8080/user/addUser1', params)
.then(function (value) {
console.log(value);
})
.catch(function (reason) {
console.log(reason);
});
})
</script>3.執(zhí)行多個并發(fā)請求
<input id="button01Id" type="button" value="點01"/>
<script>
function getUser1() {
return axios.get('http://localhost:8080/user/findById?id=1');
}
?
function getUser2() {
return axios.get('http://localhost:8080/user/findById?id=2');
}
?
$("#buttonId").click(function () {
axios.all([getUser1(), getUser2()])
.then(axios.spread(function (user1, user2) {
alert(user1.data.username);
alert(user2.data.username);
}))
})
</script>另外一種形式:
<input id="button02Id" type="button" value="點02"/>
<script>
$("#button02Id").click(function () {
axios.all([
axios.get('http://localhost:8080/user/findById?id=1'),
axios.get('http://localhost:8080/user/findById?id=2')
])
.then(axios.spread(function (user1, user2) {
alert(user1.data.username);
alert(user2.data.username);
}))
})
</script>當所有的請求都完成后,會收到一個數組,包含著響應對象,其中的順序和請求發(fā)送的順序相同,可以使用axios.spread分割成多個單獨的響應對象
三、 axiosAPI
(一)可以通過向axios傳遞相關配置來創(chuàng)建請求
axios(config)
<input id="buttonId" type="button" value="點"/>
<script>
$("#buttonId").click(function () {
var params = new URLSearchParams();
params.append('username','trewwe');
params.append('password','wertyu');
// 發(fā)起一個post請求
axios({
method:'post',
url:'http://localhost:8080/user/addUser1',
data:params
});
})
</script>axios(url[,config])
<input id="buttonId" type="button" value="點"/>
<script>
$("#buttonId").click(function () {
// 發(fā)起一個get請求,(get是默認的請求方法)
axios('http://localhost:8080/user/getWord');
})
</script>(二)請求方法別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[,config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])在使用別名方法時,url、method、data這些屬性都不必在配置中指定
(三)并發(fā)請求,即是幫助處理并發(fā)請求的輔助函數
//iterable是一個可以迭代的參數如數組等 axios.all(iterable) //callback要等到所有請求都完成才會執(zhí)行 axios.spread(callback)
(四)創(chuàng)建實例,使用自定義配置
1.axios.create([config])
var instance = axios.create({
baseURL:"http://localhost:8080/user/getWord",
timeout:1000,
headers: {'X-Custom-Header':'foobar'}
});2.實例的方法
以下是實例方法,注意已經定義的配置將和利用create創(chuàng)建的實例的配置合并
axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch(url[,data[,config]])
四、請求配置
請求的配置選項,只有url選項是必須的,如果method選項未定義,那么它默認是以get方式發(fā)出請求
{
// url 是用于請求的服務器 URL
url: '/user/getWord',
?
// method 是創(chuàng)建請求時使用的方法
method: 'get', // 默認是 get
?
// baseURL 將自動加在 url 前面,除非 url 是一個絕對路徑。
// 它可以通過設置一個 baseURL 便于為 axios 實例的方法傳遞相對路徑
baseURL: 'http://localhost:8080/',
?
// transformRequest 允許在向服務器發(fā)送前,修改請求數據
// 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
// 后面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
transformRequest: [function (data) {
// 對 data 進行任意轉換處理
?
return data;
}],
?
// transformResponse 在傳遞給 then/catch 前,允許修改響應數據
transformResponse: [function (data) {
// 對 data 進行任意轉換處理
?
return data;
}],
?
// headers 是即將被發(fā)送的自定義請求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
?
// params 是即將與請求一起發(fā)送的 URL 參數
// 必須是一個無格式對象(plain object)或 URLSearchParams 對象
params: {
ID: 12345
},
?
// paramsSerializer 是一個負責 params 序列化的函數
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
?
// data 是作為請求主體被發(fā)送的數據
// 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'
// 在沒有設置 transformRequest 時,必須是以下類型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專屬:FormData, File, Blob
// - Node 專屬: Stream
data: {
firstName: 'yuyao'
},
?
// timeout 指定請求超時的毫秒數(0 表示無超時時間)
// 如果請求話費了超過 timeout 的時間,請求將被中斷
timeout: 1000,
?
// withCredentials 表示跨域請求時是否需要使用憑證
withCredentials: false, // 默認的
?
// adapter 允許自定義處理請求,以使測試更輕松
// 返回一個 promise 并應用一個有效的響應 (查閱 [response docs](#response-api)).
adapter: function (config) {
/* ... */
},
?
// auth 表示應該使用 HTTP 基礎驗證,并提供憑據
// 這將設置一個 Authorization 頭,覆寫掉現(xiàn)有的任意使用 headers 設置的自定義 Authorization 頭
auth: {
username: 'zhangsan',
password: '12345'
},
?
// responseType 表示服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // 默認的
?
// xsrfCookieName 是用作 xsrf token 的值的cookie的名稱
xsrfCookieName: 'XSRF-TOKEN', // default
?
// xsrfHeaderName 是承載 xsrf token 的值的 HTTP 頭的名稱
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的
?
// onUploadProgress 允許為上傳處理進度事件
onUploadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
?
// onDownloadProgress 允許為下載處理進度事件
onDownloadProgress: function (progressEvent) {
// 對原生進度事件的處理
},
?
// maxContentLength 定義允許的響應內容的最大尺寸
maxContentLength: 2000,
?
// validateStatus 定義對于給定的HTTP 響應狀態(tài)碼是 resolve 或 reject promise 。
// 如果 validateStatus 返回 true (或者設置為 null 或 undefined ),promise 將被 resolve; 否則,promise 將被 rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認的
},
?
// maxRedirects 定義在 node.js 中 follow 的最大重定向數目
// 如果設置為0,將不會 follow 任何重定向
maxRedirects: 5, // 默認的
?
// httpAgent 和 httpsAgent 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
// keepAlive 默認沒有啟用
httpAgent: new http.Agent({keepAlive: true}),
httpsAgent: new https.Agent({keepAlive: true}),
?
// 'proxy' 定義代理服務器的主機名稱和端口
// auth 表示 HTTP 基礎驗證應當用于連接代理,并提供憑據
// 這將會設置一個 Proxy-Authorization 頭,覆寫掉已有的通過使用 header 設置的自定義 Proxy-Authorization 頭。
proxy: {
host: '127.0.0.1',
port: 9000,
auth: {
username: 'lisi',
password: '54321'
}
},
?
// cancelToken 指定用于取消請求的 cancel token
cancelToken: new CancelToken(function (cancel) {
})
}五、響應內容
{
data:{},
status:200,
//從服務器返回的http狀態(tài)文本
statusText:'OK',
//響應頭信息
headers: {},
//config是在請求的時候的一些配置信息
config: {}
}可以這樣來獲取響應信息
<input id="getId" type="button" value="get"/>
<script>
$("#getId").click(function () {
axios.get('http://localhost:8080/user/findById?id=1')
.then(function (value) {
console.log("data:"+value.data);
console.log("status:"+value.status);
console.log("statusText:"+value.statusText);
console.log("headers:"+value.headers);
console.log("config:"+value.config);
})
.catch(function (reason) {
console.log(reason);
})
})
</script>六、默認配置
默認配置對所有請求都有效
1、全局默認配置
axios.defaults.baseURL = 'http://localhost:8080/'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
2、自定義的實例默認設置
//當創(chuàng)建實例的時候配置默認配置
var instance = axios.create({
baseURL: 'http://localhost:8080/'
});
//當實例創(chuàng)建時候修改配置
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;3、配置中有優(yōu)先級
config配置將會以優(yōu)先級別來合并,順序是lib/defauts.js中的默認配置,然后是實例中的默認配置,最后是請求中的config參數的配置,越往后等級越高,后面的會覆蓋前面的例子。
//創(chuàng)建一個實例的時候會使用libray目錄中的默認配置
//在這里timeout配置的值為0,來自于libray的默認值
var instance = axios.create();
//回覆蓋掉library的默認值
//現(xiàn)在所有的請求都要等2.5S之后才會發(fā)出
instance.defaults.timeout = 2500;
//這里的timeout回覆蓋之前的2.5S變成5s
instance.get('/longRequest',{
timeout: 5000
});七、攔截器
1.可以在請求、響應在到達then/catch之前攔截
//添加一個請求攔截器
axios.interceptors.request.use(function(config){
//在請求發(fā)出之前進行一些操作
return config;
},function(err){
//Do something with request error
return Promise.reject(error);
});
//添加一個響應攔截器
axios.interceptors.response.use(function(res){
//在這里對返回的數據進行處理
return res;
},function(err){
//Do something with response error
return Promise.reject(error);
})2.取消攔截器
var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);3.給自定義的axios實例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function(){})八、錯誤處理
<input id="getId" type="button" value="get"/>
<script>
$("#getId").click(function () {
axios.get('http://localhost:8080/user/findById?id=100')
.catch(function (error) {
if (error.response) {
//請求已經發(fā)出,但是服務器響應返回的狀態(tài)嗎不在2xx的范圍內
console.log("data:"+error.response.data);
console.log("status:"+error.response.status);
console.log("header:"+error.response.header);
} else {
//一些錯誤是在設置請求的時候觸發(fā)
console.log('Error', error.message);
}
console.log(error.config);
});
})
</script>九、取消
通過一個cancel token來取消一個請求
通過CancelToken.source工廠函數來創(chuàng)建一個cancel token
<input id="getId" type="button" value="get"/>
<input id="unGetId" type="button" value="unGet"/>
<script>
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
$("#getId").click(function () {
axios.get('http://localhost:8080/user/findById?id=1', {
cancelToken: source.token
})
.then(function (value) {
console.log(value);
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
//handle error
}
});
});
$("#unGetId").click(function () {
//取消請求(信息的參數可以設置的)
source.cancel("操作被用戶取消");
});
</script>到此這篇關于axios get post請求 傳遞參數的文章就介紹到這了,更多相關axios get post請求 傳遞參數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解微信小程序開發(fā)—你期待的分享功能來了,微信小程序序新增5大功能
微信小程序在12月21日發(fā)布了新版本的開發(fā)工具,并在官網公布新增分享、模板消息、客服消息、掃一掃、帶參數二維碼功能。2016-12-12

