格式类型
form-data
application/x-www-form-urlencoded
application/json
text/xml
一、form-data
-
multipart/form-data: 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分,这个一般文件上传时用。
-
当method为post时候,浏览器把form数据封装到http body中,然后发送到server。
-
如果没有type=file的控件,默认用application/x-www-form-urlencoded。
-
如果有type=file,必须用multipart/form-data。
调用接口的时候参数data等于formData,用console.log打印formdata为空,其实是有数据的
const formData = new FormData();
formData.append('name', '李雷');
// 使用get方法查看数据
formData.get('modelName') // code
二、application/x-www-form-urlencoded
①请求方式为get:
当method为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2…),然后把这个字串append到url后面,用?分割,加载这个新的url,可以传json对象格式
②post
为post的情况需要传form-data格式, 窗体数据被编码为名称/值对,这是标准的编码格式
1.可以new FormData()
2.可以使用 qs.stringify() 转成键值的格式
qs需安装 命令:npm run qs
let obj ={name:'Cathy',age:100}
let qsResult = qs.stringify(obj) // name=Cathy&age=100
let jsonResult = JSON.stringify(obj) // '{"name":"Cathy","age":100}'
aaa(qsResult).then(res=》{}}
需要手动修改content-type
export function listTreeByDimensionId(query) {
return request({
url: '/setup/kgceDimensionTree/listTreeByDimensionId',
method: 'post',
data: query,
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
})
}
三、application/json
普通json格式传参
四、text/xml
是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。
是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范
四、Content-Type的使用
客户端发送请求(Request)时的Content-Type设置,特别是使用ajax的时候,如果设置得不准确,很有可能导致请求失败。
- 如果是一个restful接口(json格式),一般将Content-Type设置为application/json; charset=UTF-8;
- 如果是文件上传,一般Content-Type设置为multipart/form-data
- 如果普通表单提交,一般Content-Type设置为application/x-www-form-urlencoded
参考:https://blog.csdn.net/qq_45796667/article/details/125239247
遇到问题:
1.get请求修改Content-Type无效
请求方法中设置了请求头Content-Type,request headers中没有更改成功
export function detailBy() {
return request({
url: '/setup/kgceDimension/detail',
method: 'get',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
})
}
2.问题原因:
npm下axios的源码中,当未设置请求数据的时候会删掉Content-Type的设置
3.解决方法
config.data = true
/**
* request interceptor 发送请求时拦截
*/
service.interceptors.request.use(
config => {
if (!config.data) {
config.data = true // 解决请求没有参数时添加不上Content-Type问题
}
// config.headers['Content-type'] = 'application/json;charset=UTF-8'
config.headers['Authorization-Idaas'] = getToken()
return config
},
error => {
// do something with request error
return Promise.reject(error)
}
)
2.axios封装问题
不要设备默认Content-type,因为遇到不同的请求类型时,会被覆盖,修改无效。axios默认Content-type为application/json
/**
* request interceptor 发送请求时拦截
*/
service.interceptors.request.use(
config => {
// config.headers['Content-type'] = 'application/json;charset=UTF-8'//不要设备默认Content-type
config.headers['Authorization-Idaas'] = getToken()
return config
},
error => {
// do something with request error
return Promise.reject(error)
}
)
3. axios默认headers content-type问题
①传参为对象,请求头的content-type是application/json;charset=UTF-8
②发送一个上传文件的请求formdata,请求头的content-type是multipart/form-data
参考:https://blog.csdn.net/u010856177/article/details/127074333