axios请求头中的Content-Type 服务器在收到http请求的时候,怎么去解析参数,是请求头header中的Content-Type规定的,也就是内容类型。不同形式的参数设置不同类型的请求头。 axios请求方法'post', 'put', 'patch'如果传参data是json对象,那么请求头就会更改为Content-Type':application/json;charset=utf-8'。此时Servlet无法通过request.getParameter()接收,得到的是null值。
Content-Type: application/json
这种是axios默认的请求数据类型,如果使用Spring的@RequestBody可以直接获取,只需将参数json对象传递即可,无需多余的配置。但Servlet处理不了,前端需要额外的代码。
第一种方法:修改全局请求头,添加默认请求头'Content-Type': 'application/x-www-form-urlencoded'。 axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; axios.post("UserServlet/axiosLogin", user) 或修改请求头 axios.post("UserServlet/axiosLogin",user,{ headers: { 'content-type': 'application/x-www-form-urlencoded' } }).then(function(res){ console.log(res.data); }).catch(function (error) { console.log(error); }); 第二种方法:使用包装对象 let params = new URLSearchParams(); params.append('username', user.username) params.append('password', user.password) axios.post("UserServlet/axiosLogin", params) 第三种方法:使用Qs转成字符串 <script src="https://unpkg.com/@element-plus/icons-vue@2.0.10/dist/index.iife.min.js"></script> axios.post("UserServlet/axiosLogin", Qs.stringify(user))
Axios请求头中的Content-Type常见的有3种:
1.Content-Type:application/json
2.Content-Type:application/x-www-form-urlencoded
3.Content-Type:multipart/form-data
用post时,用data传参不在地址中显示参数,用params传参在地址中显示参数
用get时,用data传参无法传参数,必须明确用params传参。
Qs互转
let url='userId=admin&password=123456';
// 转为对象
console.log(Qs.parse(url));
let person = {name:'zhangsf',age:19};
// 转为url参数形式
console.log(Qs.stringify(person));
Content-Type:multipart/form-data,则一般用来上传文件,指定传输数据为二进制数据,例如图片、mp3、文件,也可以用来上传键值对。
<input type="file" name="pic" />
let data = new FormData();
data.append('pic', document.querySelector('input[type=file]').files[0]);
data.append('username', 'admin');
data.append('password', '123456');
axios({
url: '/UserServlet/insert',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
},
data: data
})