[英]POST parameters in Vue request to Java Servlet not getting through to Servlet?
我目前正在學習 Vue,並試圖將一些 post 變量發送到一個簡單的 Java servlet。 但是,當我嘗試訪問它們時,所有對 getParameter 的調用都以 NULL 的形式出現。
我使用以下代碼發送發布請求:
let formData = new FormData();
formData.append('brukernavn',this.skjema.brukernavn);
formData.append('passord',this.skjema.passord);
console.log(formData);
axios.post('/BoardgamesRegister/ajax/login',formData)
.then(function(response){
console.log(response);
})
.catch(function(error){
});
但是,當我嘗試使用此代碼在服務器端訪問這些變量時,我只是將 NULL 作為值。
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException {
System.out.println(req.getParameter("brukernavn"));
System.out.println(req.getParameter("passord"));
this.executeRequest(req,res,pw,null);
}
問題是,如果我嘗試將 GET 參數添加到 URL 以進行調用,則 getParameter 方法會正確獲取該值。 因此,我的 POST 變量似乎以某種方式丟失了請求。 我的 Vue 代碼有問題還是服務器端有問題? 我嘗試通過請求參數進行枚舉,並且只顯示了獲取參數,而不是發布參數。
這似乎是 Java Servlet 中的一個問題,因為當我嘗試將請求發送到 PHP 腳本時,POST 參數被正確提取。
@Tim 的評論不是問題,但它確實引領了正確的道路。 我不知何故錯過了 Axios 自動將調用后參數加密到 JSON 中。 所以在正常的 POST 請求中,getParameter 確實可以工作,但在這里不行。 所以現在,我只需要找到一種方法來阻止 Axios 轉換為 JSON。
唔。 我通常這樣做的方法是定義一個 class ,它是輸入數據(數據傳輸對象)的 DTO,我把它作為定義為 REST 的方法的參數(連同 @RequestBody 注釋)通過@PostMapping 端點。
@PostMapping("/thingDetail")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 500, message = "Internal Server Error")
})
@ApiOperation(value = "Get detail information about a thing.")
public ThingDetailsDTO getThingDetails(@RequestBody ThingDetailsRequestDTO requestDto)
{
return thingService.getDetails(requestDto);
}
但是,如果您沒有使用 Spring 引導和注釋來控制它,我懷疑您的操作級別錯誤。 我認為您需要向 HttpServletRequest.getParameter 詢問“postData”或類似的東西,它本身就是 map。 我建議您在調試器中暫停並查看 req 的參數部分中的內容,或者使用 printf 記錄 req.getParameters() 中的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.