ポストリクエストでフォームデータ形式を設定するいくつかの方法

デフォルトの post メソッドを使用してデータを送信すると、バックエンドがデータを取得できないことがわかりましたが、ネットワークではパラメーターが実際に渡されていることがわかりました。両者の違いを比較した結果、postman は form-data 形式を使用していることがわかったので、form-data 形式を使用して再度リクエストしたところ、OJBK であることがわかりました。

どちらの形式も使用できません。

 

方法 1:transformRequest を構成する

欠点: 他のリクエスト形式のデータも再フォーマットされます (PUT、PATCH)。

import axios from "axios"  //引入

//设置axios为form-data
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function (data) {
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
}]


//然后再修改原型链
Vue.prototype.$axios = axios

次のような直接の引用もあります。

axios({
   method: 'post',
   url: 'http://localhost:8080/login',
   data: {
      username: this.loginForm.username,
      password: this.loginForm.password
   },
   transformRequest: [
      function (data) {
         let ret = ''
         for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
         }
         ret = ret.substring(0, ret.lastIndexOf('&'));
         return ret
      }
    ],
    headers: {
       'Content-Type': 'application/x-www-form-urlencoded'
    }
})

方法 2: リクエスト インターセプターを追加し、適切な薬を処方する (推奨)

すべての主要なブラウザは encodeURIComponent() 関数をサポートしています

カプセル化された axios に次のコードを追加します。

//添加请求拦截器
axios.interceptors.request.use(
	config => {
		//设置axios为form-data 方法2
		if (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);
	}
);

 これが現在の形式です

 

おすすめ

転載: blog.csdn.net/weixin_52691965/article/details/124691838