前端使用 axios傳送資料,後端servlet無法獲取的問題
阿新 • • 發佈:2021-11-17
問題
前端傳送請求
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部落格