前端使用 axios發送數據,后端servlet無法獲取的問題


問題

前端發送請求

axios({
    url:'http://localhost:8080/javaWeb/RegisController',
    method: 'POST',
    data:{
        username:user.value,
        password:truePwd.value,
        checkData:trueCode.value
    }
})

后端收到的

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    //得到請求參數
    String username =req.getParameter("username");
    String password =req.getParameter("password");
    String trueCode =req.getParameter("checkData");


    System.out.println(username);//null
    System.out.println(password);//null
    System.out.println(trueCode);//null
    
    
}

請求頭的問題

解決問題

后端解決

通過流來讀取

  @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = req.getReader();
        char[] buf = new char[1024];
        int len;
        while ((len = reader.read(buf)) != -1){
            sb.append(buf,0,len);
        }
     System.out.println(sb.toString());
  }

前端解決

通過特定的格式來進行傳遞參數 不需要設置修改請求頭什么等等花里胡哨的的操作

URLSearchParams:處理請求參數用的

let params = new URLSearchParams();
params.append('username', user.value);
params.append('password', truePwd.value);
params.append('checkData', trueCode.value);

axios.post('http://localhost:8080/javaWeb/RegisController', params)
    .then(response => {
    location.href="./home.html"
}, reason => {
    alert('驗證碼錯誤,請重試!');
    addData();
})

參考文檔:(11條消息) vue中用axios發送請求 后端是servlet POST接收參數空_魏天的博客-CSDN博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM