练习axios发送添加请求的时候,出现了空指针异常。
insertOrUpdateGood:function(){
let that = this;
axios({
method: "post",
url: "goods/insertOrUpdateGood",
data: this.form
}).then(function (response) {
console.log(response.message);
that.dialogFormVisible = false;
that.loadData();
},
(error) => {
console.log("错误", error);
}
);
}
打开F12可以看到如果不自己设置请求头,它自己默认的请求头如下:
因为后端采用的是servlet,所以无法像框架那样通过添加注解来接收指定参数,这个时候后端使用,这时Map
解决办法:通过流来读取数据
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader reader = req.getReader();
String str = null;
while ((str = reader.readLine()) != null) {
stringBuffer.append(str);
}
str = stringBuffer.toString();
Goods goods = JSONObject.parseObject(str, Goods.class);
Message msg = null;
Integer i = null;
if(goods.getId() == null){
i = goodDao.addGoodInfo(goods);
if (i > 0) {
msg = new Message("新增成功", true, null);
resp.getWriter().write(JSON.toJSONString(msg));
} else {
msg = new Message("新增失败", false, null);
resp.getWriter().write(JSON.toJSONString(msg));
}
}
else {
i = goodDao.updateGoodById(goods);
if (i > 0) {
msg = new Message("修改成功", true, null);
resp.getWriter().write(JSON.toJSONString(msg));
} else {
msg = new Message("修改失败", false, null);
resp.getWriter().write(JSON.toJSONString(msg));
}
}
}



