vue全局使用emulateJSON对象
一、解释
如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。
启用该选项后,请求会以application/x-www-form-urlencoded
作为Content-Type,就像普通的HTML表单一样
二、代码
// 全局启用 emulateJSON 选项
Vue.http.options.emulateJSON = true; this.$http.post('api/addproduct', { name: this.name } ).then(result => { if (result.body.status === 0) { // 成功了! // 添加完成后,只需要手动,再调用一下 getAllList 就能刷新品牌列表了 this.getAllList() // 清空 name this.name = '' } else { // 失败了 alert('添加失败!') } })
没有全局启用代码
this.$http.post('api/addproduct', { name: this.name }, { emulateJSON: true }).then(result => { if (result.body.status === 0) { // 成功了! // 添加完成后,只需要手动,再调用一下 getAllList 就能刷新品牌列表了 this.getAllList() // 清空 name this.name = '' } else { // 失败了 alert('添加失败!') } })
三、vue axios发送Form Data格式数据请求
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'
1、设置单个的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'
2、全局设置POST请求为 Form Data 格式
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 引入即可使用。