【发布时间】:2020-02-06 08:09:23
【问题描述】:
我有一个 java servlet CRUD 应用程序。当我使用邮递员时,GET、POST、PUT 和 DELETE 工作。但是当我使用我的前端 javascript 代码时,只有 GET 请求会起作用。正在到达 servlet 后端上的 POST、PUT 和 DELETE 方法,但是当它到达后端时,它似乎没有附加任何参数。
下面是我的 GET JS 代码。
function getTimePeriods(){
clearElements()
const url = 'http://localhost:8080/TimeTrackerWServlets/TimePeriodController/'
fetch(url)
.then(response => response.json())
.then(response => showTimePeriods(response))
}
下面是 POST JS 代码。
function post(){
console.log("post file reached")
const url = 'http://localhost:8080/TimeTrackerWServlets/TimePeriodController/'
const Data = {
timePeriodId: "999",
activityType: "ANIME"
};
const otherPram = {
headers: {
"content-type" : "application/json; charset=UTF - 8"
},
body : Data, //JSON.stringify(Data)
method: "POST",
// mode: "no-cors",
};
fetch(url, otherPram)
.then(data=>{return data.json})
.then(res=>console.log(res))
.catch(error=>console.log(error))
}
我可以 console.log 我想附加到请求的对象很好。
下面是我的 servlet doPost 方法的简化版本。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost reached POST POST POST POST POST POST POST POST ");
setAccessControlHeaders(response);
System.out.println("startTime: " + request.getParameter("timePeriodId"));
System.out.println("startTime: " + request.getParameter("activityType"));
}
两个
System.out.println("startTime: " + request.getParameter("timePeriodId")); ---> null
System.out.println("startTime: " + request.getParameter("activityType")); ---> null
打印出null。
那么我如何将数据附加到前端的请求中。你是我唯一的希望 Obi-Wan Kenobi。
【问题讨论】:
标签: javascript http-post fetch postman crud