使用 axios 发送请求到servlet ,后端数据接收为null

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
})

Axios请求头中常见的Content-Type及其使用 - 他好像一条狗啊 - 博客园

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rosyouth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值