axios的使用記錄以及實現上傳圖片
阿新 • • 發佈:2020-11-18
瞭解axios配置優先順序
瞭解axios的API和請求配置使用
axios中文文件:http://www.axios-js.com/zh-cn/docs/#axios-request-config-1
請求配置:
{ // `url` 是用於請求的伺服器 URL url: '/user', // `method` 是建立請求時使用的方法 method: 'get', // default // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 // 它可以通過設定一個 `baseURL` 便於為 axios 例項的方法傳遞相對 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允許在向伺服器傳送前,修改請求資料 // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 // 後面陣列中的函式必須返回一個字串,或 ArrayBuffer,或 Stream transformRequest: [function (data, headers) { // 對 data 進行任意轉換處理 return data; }], // `transformResponse` 在傳遞給 then/catch 前,允許修改響應資料 transformResponse: [function (data) { // 對 data 進行任意轉換處理 return data; }], // `headers` 是即將被髮送的自定義請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即將與請求一起傳送的 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` 是作為請求主體被髮送的資料 // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH' // 在沒有設定 `transformRequest` 時,必須是以下型別之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 瀏覽器專屬:FormData, File, Blob // - Node 專屬: Stream data: { firstName: 'Fred' }, // `timeout` 指定請求超時的毫秒數(0 表示無超時時間) // 如果請求話費了超過 `timeout` 的時間,請求將被中斷 timeout: 1000, // `withCredentials` 表示跨域請求時是否需要使用憑證 withCredentials: false, // default // `adapter` 允許自定義處理請求,以使測試更輕鬆 // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據 // 這將設定一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設定的自定義 `Authorization`頭 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示伺服器響應的資料型別,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` 允許為上傳處理進度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` 允許為下載處理進度事件 onDownloadProgress: function (progressEvent) { // 對原生進度事件的處理 }, // `maxContentLength` 定義允許的響應內容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設定為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目 // 如果設定為0,將不會 follow 任何重定向 maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用於定義在執行 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: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用於取消請求的 cancel token // (檢視後面的 Cancellation 這節瞭解更多) cancelToken: new CancelToken(function (cancel) { }) }
配置預設值:
全域性的axios預設值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定義例項預設值
// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置的優先順序
配置會以一個優先順序進行合併。這個順序是:在 lib/defaults.js 找到的庫的預設值,然後是例項的 defaults 屬性,最後是請求的 config 引數。後者將優先於前者。這裡是一個例子:
// 使用由庫提供的配置的預設值來建立例項 // 此時超時配置的預設值是 `0` var instance = axios.create(); // 覆寫庫的超時預設值 // 現在,在超時前,所有請求都會等待 2.5 秒 instance.defaults.timeout = 2500; // 為已知需要花費很長時間的請求覆寫超時設定 instance.get('/longRequest', { timeout: 5000 });
要實現axios上傳圖片,我們要了解怎麼更改header配置,傳遞FormData
demo:
前端vue:
html:
<input
name="file"
type="file"
accept="image/png,image/gif,image/jpeg"
@change="update"
/>
methods:
update(e) {
// 獲取目標檔案
let file = e.target.files[0];
let param = new FormData(); // 建立form物件
param.append("file", file); // 通過append向form物件新增資料
param.append("upload_year", "2020"); // 新增form表單中其他資料
console.log(param.get("file")); // FormData私有類物件,訪問不到,可以通過get判斷值是否傳進去
// 方式一 post
axios.post('/api/userUpload', param, {headers: { "Content-Type": "multipart/form-data" }})
.then(res => {
if (res.data.code === 0) {
self.ImgUrl = res.data.data
}
console.log(res.data)
})
// 方式二 axios
axios({
url: "/api/userUpload",
method: "post",
data:param,
headers: { "Content-Type": "multipart/form-data" },
})
.then((res) => {
if (res.data.code === 0) {
self.ImgUrl = res.data.data;
}
console.log(res.data);
});
}
須知:axios的data引數傳遞FormData時的方式,而且multipart/form-data
必須傳遞data引數
後端程式碼不展示了,這主要是記錄,axios怎麼更改headers的Content-Type,以及怎麼傳遞FormData物件。
這裡順便記錄一下解決前端vue的跨域的操作:
vue.config.js
devServer: {
proxy: {
"/api": {
// 此處的寫法,目的是為了 將 /api 替換成 https://www.baidu.com/
target: "http://www.tp6blog.com",
// 允許跨域
changeOrigin: true,
ws: true,
pathRewrite: {
"^/api": "",
},
},
},
請求:axios.post('/api/userUpload')
注意:axios的baseurl不要配置。
部署問題: