首页前端开发HTMLVUE axios发送FormData格式数据请求

VUE axios发送FormData格式数据请求

时间2024-05-08 18:42:03发布访客分类HTML浏览66
导读:VUE axios发送FormData格式数据请求 axios 默认是 Payload 格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我们就得进行转换。Payload 和 Form Data 的主要设置是根...
VUE axios发送FormData格式数据请求 axios 默认是 Payload 格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我们就得进行转换。Payload 和 Form Data 的主要设置是根据请求头的 Content-Type 的值来的。 Payload    Content-Type: 'application/json; charset=utf-8' Form Data   Content-Type: 'application/x-www-form-urlencoded' 一、设置单个的POST请求为 Form Data 格式 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' } } ) 主要配置两个地方,transformRequest 方法进行数据格式转换, Content-Type 值改为 'application/x-www-form-urlencoded' 二、全局设置POST请求为 Form Data 格式 因为像上面那样每个请求都要配置 transformRequest 和 Content-Type 非常的麻烦,重复性代码也很丑陋,所以通常都会进行全局设置。具体代码如下 import axios from 'axios' import qs from 'qs' // 实例对象 let instance = axios.create({ timeout: 6000, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ) // 请求拦截器 instance.interceptors.request.use( config => { config.data = qs.stringify(config.data) // 转为formdata数据格式 return config } , error => Promise.error(error) ) 就是我们在封装 axios 的时候,设置请求头 Content-Type 为 application/x-www-form-urlencoded。 然后在请求拦截器中,通过 qs.stringify() 进行数据格式转换,这样每次发送的POST请求都是 Form Data 格式的数据了。 其中 qs 模块是安装 axios 模块的时候就有的,不用另行安装,通过 import 引入即可使用。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: VUE axios发送FormData格式数据请求
本文地址: https://pptw.com/jishu/655694.html
通过id查找HTML元素 JavaScript 静态方法

游客 回复需填写必要信息