You should never judge something you don't understand.
你不該該去評判你不瞭解的事物。
往期文章vue
全棧的自我修養: 001環境搭建 (使用Vue,Spring Boot,Flask,Django 完成Vue先後端分離開發)
全棧的自我修養: 002使用@vue/cli進行vue.js環境搭建
全棧的自我修養: 003Axios 的簡單使用node
Table of Contentsjquery
Axios 是一個基於 Promise 的 HTTP 庫,能夠用在瀏覽器和 node.js 中。github
Github開源地址: https://github.com/axios/axiosajax
若是你原來用過 jQuery
應該還記的 $.ajax
方法吧npm
若是按照HTTP
方法的語義來暴露資源,那麼接口將會擁有安全性和冪等性的特性,例如GET和HEAD請求都是安全的, 不管請求多少次,都不會改變服務器狀態。而GET、HEAD、PUT和DELETE請求都是冪等的,不管對資源操做多少次, 結果老是同樣的,後面的請求並不會產生比第一次更多的影響。json
下面列出了 GET
,DELETE
,PUT
, PATCH
和 POST
的典型用法:axios
axios#get(url[, config])
從方法聲明能夠看出
- 第一個參數
url
必填,爲請求的url- 第二個參數
config
選填, 關於config
的屬性見下文
GET
方法用來查詢服務資源, 不該該在這裏對服務資源進行修改
axios.get('/user?id=12345') .then(response => { // 若是成功返回(http 狀態碼在 200~300),則可獲取對應的 response console.log(response); }) .catch(error => { // 異常 console.log(error); }) .then(() => { // always executed });
let request_params = { id: 123456 } axios.get('/user', { params: request_params }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
axios#delete(url[, config])
從方法聲明能夠看出
- 第一個參數
url
必填,爲請求的url- 第二個參數
config
選填, 關於config
的屬性見下文
DELETE
用來刪除一個資源,不安全但冪等
axios.delete('/user?id=12345') .then(response => { // 若是成功返回(http 狀態碼在 200~300),則可獲取對應的 response console.log(response); }) .catch(error => { // 異常 console.log(error); }) .then(() => { // always executed });
let request_params = { id: 123456 } axios.delete('/user', { params: request_params }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
let request_params = { id: 123456 } axios.delete('/user', { data: request_params }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
axios#put(url[, data[, config]])
從方法聲明能夠看出
- 第一個參數
url
必填,爲請求的url- 第二個參數
data
選填,爲請求的參數,且在請求體中- 第二個參數
config
選填, 關於config
的屬性見下文
常見使用方式
更新資源
axios.put('/user?id=12345&name=abc') .then(response => { // 若是成功返回(http 狀態碼在 200~300),則可獲取對應的 response console.log(response); }) .catch(error => { // 異常 console.log(error); }) .then(() => { // always executed });
let request_params = { id: 123456, name: "abc" } axios.post('/user', request_params, .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
axios#post(url[, data[, config]])
從方法聲明能夠看出
- 第一個參數
url
必填,爲請求的url- 第二個參數
data
選填,爲請求的參數,且在請求體中- 第二個參數
config
選填, 關於config
的屬性見下文
常見使用方式
建立id爲123456的用戶
axios.post('/user?id=12345&name=abc') .then(response => { // 若是成功返回(http 狀態碼在 200~300),則可獲取對應的 response console.log(response); }) .catch(error => { // 異常 console.log(error); }) .then(() => { // always executed });
let request_params = { id: 123456, name: "abc" } axios.post('/user', request_params, .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
axios.patch(url[, data[, config]])
從方法聲明能夠看出
- 第一個參數
url
必填,爲請求的url- 第二個參數
data
選填,爲請求的參數,且在請求體中- 第二個參數
config
選填, 關於config
的屬性見下文
常見使用方式
更新id爲123456的用戶資源
axios.patch('/user?id=12345&name=abc') .then(response => { // 若是成功返回(http 狀態碼在 200~300),則可獲取對應的 response console.log(response); }) .catch(error => { // 異常 console.log(error); }) .then(() => { // always executed });
let request_params = { id: 123456, name: "abc" } axios.patch('/user', request_params, .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
從上面的示例中能夠看出
axios.get(url[, config]) axios.delete(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])
其中 POST
、PUT
、PATCH
的使用方式是一致的,只是方式名
和 http method
存在差別, 那他們的區別在什麼地方呢
GET:從服務器取出資源(一項或多項)。 POST:在服務器新建一個資源。 PUT:在服務器更新資源(客戶端提供改變後的完整資源)。 PATCH:在服務器更新資源(客戶端提供改變的屬性)。 DELETE:從服務器刪除資源。
application/x-www-form-urlencoded
在默認狀況下,data 中數據採用了 JSON 序列化方式,即 Content-Type: application/json
, 若是想使用 application/x-www-form-urlencoded
, 則須要作特殊處理
URLSearchParams
const params = new URLSearchParams(); params.append('id', '123456'); params.append('name', 'abc'); axios.post('/user', params);
其中 URLSearchParams 存在兼容問題,具體可見caniuse
qs
進行編碼import qs from 'qs'; axios.post('/user', qs.stringify({ id: 123456, name: "abc" }));
multipart/form-data
const form = new FormData(); form.append('id', 123456); form.append('name', "abc"); axios.post('user', form, { headers: form.getHeaders() })
{ // `data` is the response that was provided by the server // response 返回數據 data: {}, // `status` is the HTTP status code from the server response // 狀態碼 status: 200, // `statusText` is the HTTP status message from the server response // 狀態碼對應的標準message statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` // 響應頭 headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} }
{ // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `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` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js maxContentLength: 2000, // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed maxBodyLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, }
更多配置參考 https://github.com/axios/axios