axios把post的RequestPayload格式轉為formdata

方法一:配置transformRequest,缺點:其他請求格式的數據也會被重新格式化(PUT,PATCH)

const service = axios.create({//設置axios為form-data 方法1// headers: {//     post: {//         "Content-Type": "application/x-www-form-urlencoded"//     },//     get: {//         "Content-Type": "application/x-www-form-urlencoded"//     }// },transformRequest: [function (data) {let request = ''for (let item in data) {if (data[item])request += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'}return request.slice(0, request.length - 1)}]
})

方法二:添加請求攔截器,對癥下藥(推薦),所有主要瀏覽器都支持 encodeURIComponent() 函數

//添加請求攔截器
service.interceptors.request.use(config => {//設置axios為form-data 方法2if (config.method === 'post') {let data = ''for (let item in config.data) {if (config.data[item])data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'}config.data = data.slice(0, data.length - 1)}return config;},error => {console.log("在request攔截器顯示錯誤:", error.response)return Promise.reject(error);}
);

方法三:添加請求攔截器,使用axios 插件qs轉換,可能存在兼容性問題

import qs from 'qs';
//添加請求攔截器
service.interceptors.request.use(config => {//設置axios為form-data 方法2if (config.method === 'post') {config.data = qs.stringify(config.data); // npm install axios qs --save}return config;},error => {console.log("在request攔截器顯示錯誤:", error.response)return Promise.reject(error);}
);

完整代碼:

import axios from 'axios'
import store from '@/store'
import router from '@/router'
import Vue from "vue";
// import qs from 'qs';
let vue = new Vue()// create an axios instance
const service = axios.create({// index.js設置了代理(解決跨域) api = XXXbaseURL: "/api", // url = base url + request urltimeout: 5000, // request timeout// headers: {//     Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",//     Cookie: "JSESSIONID=8F611FDFEBA4FA2A1891D5929F5E8682",//     "Upgrade-Insecure-Requests": 1,//     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"// }//設置axios為form-data 方法1// headers: {//     post: {//         "Content-Type": "application/x-www-form-urlencoded"//     },//     get: {//         "Content-Type": "application/x-www-form-urlencoded"//     }// },// transformRequest: [function (data) {//     let request = ''//     for (let item in data) {//         if (data[item])//             request += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'//     }//     return request.slice(0, request.length - 1)// }]
})//添加請求攔截器,若token存在則在請求頭中加token,不存在也繼續請求
service.interceptors.request.use(config => {// 每次發送請求之前檢測都vuex存有token,那么都要放在請求頭發送給服務器,沒有則不帶token// Authorization是必須的// if (store.getters.getToken) {//     config.headers.Authorization = store.getters.getToken;// }vue.$Loading.start()//設置axios為form-data 方法2if (config.method === 'post') {// config.data = qs.stringify(config.data); // npm install axios qs --savelet data = ''for (let item in config.data) {if (config.data[item])data += encodeURIComponent(item) + '=' + encodeURIComponent(config.data[item]) + '&'}config.data = data.slice(0, data.length - 1)}return config;},error => {console.log("在request攔截器顯示錯誤:", error.response)vue.$Loading.error()return Promise.reject(error);}
);//respone攔截器
service.interceptors.response.use(response => {vue.$Loading.finish();// 在status正確的情況下,code不正確則返回對應的錯誤信息(后臺自定義為200是正確,并且將錯誤信息寫在message),正確則返回響應return response.data;},error => {vue.$Loading.error()// 在status不正確的情況下,判別status狀態碼給出對應響應if (error.response) {console.log("在respone攔截器顯示錯誤:", error.response)switch (error.response.status) {case 401://可能是token過期,清除它store.commit("delToken");router.replace({ //跳轉到登錄頁面path: '/login',// 將跳轉的路由path作為參數,登錄成功后跳轉到該路由query: { redirect: router.currentRoute.fullPath }});}}return Promise.reject(error.response);}
);export default service// axios({
//     url:'/user',                            //  `url`是服務器鏈接,用來請求用
//     method:`get`,                           //  `method`是發起請求時的請求方法
//     baseURL:'http://some-domain.com/api/',  //  `baseURL`如果`url`不是絕對地址,那么將會加在其前面。當axios使用相對地址時這個設置非常方便//     transformRequest:[function(data){       //  `transformRequest`允許請求的數據在傳到服務器之前進行轉化。只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法。數組中的最后一個函數必須返回一個字符串,一個`ArrayBuffer`,或者`Stream`
//         //依自己的需求對請求數據進行處理
//         return data;
//     }],
//     transformResponse:[function(data){      //  `transformResponse`允許返回的數據傳入then/catch之前進行處理
//         //依需要對數據進行處理
//         return data;
//     }],  
//     headers:{'X-Requested-with':'XMLHttpRequest'},//`headers`是自定義的要被發送的頭信息
//     params:{ //`params`是請求連接中的請求參數,必須是一個純對象,或者URLSearchParams對象
//         ID:12345
//     },
//     paramsSerializer: function(params){//`paramsSerializer`是一個可選的函數,是用來序列化參數,例如:(https://ww.npmjs.com/package/qs,http://api.jquery.com/jquery.param/)
//         return Qs.stringify(params,{arrayFormat:'brackets'})
//     },
//     data:{//`data`是請求提需要設置的數據,只適用于應用的'PUT','POST','PATCH',請求方法。當沒有設置`transformRequest`時,必須是以下其中之一的類型(不可重復?):-string,plain object,ArrayBuffer,ArrayBufferView,URLSearchParams。僅瀏覽器:FormData,File,Blob。僅Node:Stream
//         firstName:'fred'
//     },
//     //`timeout`定義請求的時間,單位是毫秒。
//     //如果請求的時間超過這個設定時間,請求將會停止。
//     timeout:1000,
//     //`withCredentials`表明是否跨域請求,
//     //應該是用證書
//     withCredentials:false //默認值
//     //`adapter`適配器,允許自定義處理請求,這會使測試更簡單。
//     //返回一個promise,并且提供驗證返回(查看[response docs](#response-api))
//     adapter:function(config){
//         /*...*/
//     },
//     //`auth`表明HTTP基礎的認證應該被使用,并且提供證書。
//     //這個會設置一個`authorization` 頭(header),并且覆蓋你在header設置的Authorization頭信息。
//     auth:{
//         username:'janedoe',
//         password:'s00pers3cret'
//     },
//     //`responsetype`表明服務器返回的數據類型,這些類型的設置應該是
//     //'arraybuffer','blob','document','json','text',stream'
//     responsetype:'json',
//     //`xsrfHeaderName` 是http頭(header)的名字,并且該頭攜帶xsrf的值
//     xrsfHeadername:'X-XSRF-TOKEN',//默認值
//     //`onUploadProgress`允許處理上傳過程的事件
//     onUploadProgress: function(progressEvent){
//         //本地過程事件發生時想做的事
//     },
//     //`onDownloadProgress`允許處理下載過程的事件
//     onDownloadProgress: function(progressEvent){
//         //下載過程中想做的事
//     },
//     //`maxContentLength` 定義http返回內容的最大容量
//     maxContentLength: 2000,
//     //`validateStatus` 定義promise的resolve和reject。
//     //http返回狀態碼,如果`validateStatus`返回true(或者設置成null/undefined),promise將會接受;其他的promise將會拒絕。
//     validateStatus: function(status){
//         return status >= 200 &;&; stauts < 300;//默認
//     },
//     //`httpAgent` 和 `httpsAgent`當產生一個http或者https請求時分別定義一個自定義的代理,在nodejs中。
//     //這個允許設置一些選選個,像是`keepAlive`--這個在默認中是沒有開啟的。
//     httpAgent: new http.Agent({keepAlive:treu}),
//     httpsAgent: new https.Agent({keepAlive:true}),
//     //`proxy`定義服務器的主機名字和端口號。
//     //`auth`表明HTTP基本認證應該跟`proxy`相連接,并且提供證書。
//     //這個將設置一個'Proxy-Authorization'頭(header),覆蓋原先自定義的。
//     proxy:{
//         host:127.0.0.1,
//         port:9000,
//         auth:{
//             username:'cdd',
//             password:'123456'
//         }
//     },
//     //`cancelTaken` 定義一個取消,能夠用來取消請求
//     //(查看 下面的Cancellation 的詳細部分)
//     cancelToke: new CancelToken(function(cancel){
//     })
// });

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278609.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278609.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278609.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

火狐打印預覽_將打印和打印預覽命令添加到Firefox的上下文菜單

火狐打印預覽Have you been thinking about how much easier it would be to having the Print & Print Preview commands in Firefox’s Context Menu? The Print Context Menu extension for Firefox allows you to avoid having to use the File Menu to access the pr…

每個人都要在自己的“時區”里找到自己的快樂

祝小妹和自己生日快樂&#xff0c;人人都想快樂&#xff0c;卻在平常的365天悶悶不樂&#xff0c;但愿家人朋友在平常的每一天都很夠健康快樂&#xff01; 在我那個開不了機的手機記事薄有句話還記得&#xff1a;你們不要刻意等我&#xff0c;因為可能現在的我還沒來得及去發現…

《2017 云計算評測報告》:帶你了解 AWS、阿里云、騰訊云等八家云計算服務提供商的綜合用戶體驗情況...

報告電子版至聽云官方博客下載&#xff1a;http://blog.tingyun.com/web/article/detail/1352 評測說明 評測目標&#xff1a;同一應用&#xff08;網站&#xff09;在不同云上的用戶訪問體驗&#xff0c;以及對云資源的使用 洞察周期及范圍&#xff1a;2017年4月-2017年9月 訪…

js以變量為鍵

let key "dynamic",obj{[key]:true }; obj[key2]key console.log(obj)一般在配置文件中應用較多

搭建jenkins實現自動化部署

參考&#xff1a; https://www.cnblogs.com/rslai/p/8135460.html轉載于:https://www.cnblogs.com/lihuanhuan/p/10612123.html

python 新聞摘要_每日新聞摘要:Microsoft內部禁止應用程序,這樣就可以了

python 新聞摘要Recently, a list of apps that Microsoft prohibits for internal employee use leaked, including Slack, Grammarly, and others. It’s tempting to think these are the actions of a company hating competition, but the truth is more complicated. 最近…

vue使用process.env搭建自定義運行環境

一、vue-cli項目下默認有三種模式&#xff1a; development&#xff1a;在 vue-cli-service serve 時使用。production&#xff1a;在 vue-cli-service build 和 vue-cli-service test:e2e 時使用。test&#xff1a;在 vue-cli-service test:unit 時使用。 對應的 process.env…

bootstrap評分插件 Bootstrap Star Rating Examples

http://www.jq22.com/demo/bootstrap-star-rating-master201708041812/ 轉載于:https://www.cnblogs.com/waw/p/8288951.html

http 請求報文

1、報文 2、http請求方法 restful接口 post&#xff1a;創建 put&#xff1a;更新 轉載于:https://www.cnblogs.com/mengfangui/p/10171559.html

chrome硬件加速_如何在Chrome中打開和關閉硬件加速

chrome硬件加速Google Chrome comes equipped with hardware acceleration, a feature which takes advantage of your computer’s GPU to speed up processes and free vital CPU time. However, sometimes driver incompatibilities can cause this feature to misbehave an…

春節您“搶票”到手了嗎,如果沒,請進來看看!

不是為了賣“廣告”!我與軟件作者從不認識&#xff01;我與軟件作者因為搶票認識&#xff0c;不&#xff0c;只認識他寫的軟件&#xff01;51CTO博客2.0后&#xff0c;我一直沒有寫博文&#xff01;主要原因&#xff1a;不能用Live Writer寫博文&#xff0c;復制&#xff0c;粘…

兩個矩陣相加 Exercise08_05

1 import java.util.Scanner;2 /**3 * author 冰櫻夢4 * 時間&#xff1a;2018年12月5 * 題目&#xff1a;兩個矩陣相加6 *7 */8 public class Exercise08_05 {9 public static void main(String[] args){ 10 Scanner inputnew Scanner(System.in); 11 …

vue element form中input等組件不能輸入值

<el-input v-model"form.inputVal " />由于data中form只是一個空對象{}&#xff0c;當主動設置 form.inputVal “” 后input卻仍無法輸入值&#xff0c;這是因為inputVal 屬性沒有get和set&#xff0c;需要用vue內置屬性設置&#xff1a;this.$set(this.form,…

如何在PowerPoint中制作三折

While Microsoft PowerPoint is almost exclusively used for presentation purposes, it’s also a great application for creating interesting and visually appealing brochures. Here’s how to create (and print out) a tri-fold using PowerPoint. 盡管Microsoft Powe…

徹底理解數據庫事物

事務 事務(Transaction)&#xff0c;一般是指要做的或所做的事情。在計算機術語中是指訪問并可能更新數據庫中各種數據項的一個程序執行單元(unit)。在計算機術語中&#xff0c;事務通常就是指數據庫事務。 概念 一個數據庫事務通常包含對數據庫進行讀或寫的一個操作序列。它的…

HttpRunner自動化框架學習筆記

一.簡單介紹 HttpRunner 是一款面向 HTTP(S) 協議的通用測試框架&#xff0c;只需編寫維護一份 YAML/JSON 腳本&#xff0c;即可實現自動化測試、性能測試、線上監控、持續集成等多種測試需求。 支持python2和python3 二.框架特點 繼承 Requests 的全部特性&#xff0c;輕松實現…

如何在Chrome中為Gmail啟用桌面通知

Last year Google rolled out desktop notifications for Google Calendar, now you can get Gmail and Gchat notifications on your desktop too. Read on as we walk you through configuring them both. 去年Google推出了Google日歷的桌面通知&#xff0c;現在您也可以在桌…

vue集成iconfont、fontawesome和圖標選擇器(含fontawesome、el-icon和加入的iconfont)

目錄&#xff08;一&#xff09;引入iconfont字體圖標庫將圖標加入購物車新建&#xff08;添加至&#xff09;項目下載后項目中引入&#xff08;二&#xff09;引入fontawesome&#xff08;三&#xff09;圖標選擇器效果圖結構使用源碼&#xff08;一&#xff09;引入iconfont字…

java之Synchronize

2019獨角獸企業重金招聘Python工程師標準>>> 實現原理&#xff1a;JVM 是通過進入、退出對象監視器( Monitor )來實現對方法、同步塊的同步的。 具體實現是在編譯之后在同步方法調用前加入一個 monitor.enter 指令&#xff0c;在退出方法和異常處插入 monitor.exit …

pop()方法

pop()方法 描述 列表 pop() 方法通過指定元素的索引值來移除列表中的某個元素&#xff08;默認是最后一個元素&#xff09;&#xff0c;并且返回該元素的值&#xff0c;如果列表為空或者索引值超出范圍會報一個異常。 語法 pop() 方法語法&#xff1a; L.pop([index-1]) 參數 i…