axios 發 post 請求,後端接收不到引數的詳細解決方案
問題描述 :axios post 請求或者get請求後接收不到引數
後端接收設定: @RequestParam @RequestBody設定的原因
由於spring的RequestParam註解接收的引數是來自於requestHeader中,即請求頭,也就是在url中,格式為xxx?username=123&password=456,而RequestBody註解接收的引數則是來自於requestBody中,即請求體中。
---------------------------------------------------------------------------------------
前端用axios傳送請求:
Content-Type預設是
application/json;charset=UTF-8
而伺服器是
'Content-Type': 'application/x-www-form-urlencoded'
原理剖析在最後
後端 解決方案:
前端解決方案
https://blog.csdn.net/csdn_yudong/article/details/79668655
一:
如果為get請求時,後臺接收引數的註解應該為RequestParam,如果為post請求時,則後臺接收引數的註解就是為RequestBody。附上兩個例子,截圖如下:
get請求
@RequestMapping(value = "/anaData") public String selectOrderInfo(@RequestParam("method") String method, @RequestParam Map<String,Object> params) { LOG.debug(TextUtils.format("/***資料 分析模組,統計查詢 通用方法{0}**/", method)); return analysisClientService.selectOrderInfo(method,params); }
post請求
@PostMapping(value = "/center")
public String requestApi(@RequestBody Map<String, Object> params){
loger.debug(TextUtils.format("呼叫開始------"));
return apiCenterClientService.requestApi(params);
}
二、複雜引數形式
未完待續。。。。。。。
tips:如果引數 有HttpServletRequest需要 注入可以用下面方式
在Controller中注入了HttpServletRequest,形式如下所示:
@RestController
public class AutowiredRequestController {
@Autowired
private HttpServletRequest request;
}
不會有執行緒安全問題!Controller層中所注入的HttpServletReuqest的實現類為JDK動態代理生成的一個代理類,從Request中獲取值的時候是從ThreadLocal中得到的物件中的值。
----------------------------------------------------------------------未處理部分-----------------------------------------
@RequestParam
用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容。提交方式為get或post。(Http協議中,如果不指定Content-Type,則預設傳遞的引數就是application/x-www-form-urlencoded型別)
RequestParam實質是將Request.getParameter() 中的Key-Value引數Map利用Spring的轉化機制ConversionService配置,轉化成引數接收物件或欄位。
get方式中query String的值,和post方式中body data的值都會被Servlet接受到並轉化到Request.getParameter()引數集中,所以@RequestParam可以獲取的到
@RequestBody
處理HttpEntity傳遞過來的資料,一般用來處理非Content-Type: application/x-www-form-urlencoded編碼格式的資料。
GET請求中,因為沒有HttpEntity,所以@RequestBody並不適用。
POST請求中,通過HttpEntity傳遞的引數,必須要在請求頭中宣告資料的型別Content-Type,SpringMVC通過使用HandlerAdapter 配置的HttpMessageConverters來解析HttpEntity中的資料,然後繫結到相應的bean上。
@RequestBody用於post請求,不能用於get請求
這裡涉及到使用@RequestBody接收不同的物件
1. 建立一個新的entity,將兩個entity都進去。這是最簡單的,但是不夠“優雅”。
2. 用Map<String, Object>接受request body,自己反序列化到各個entity中。
3. 類似方法2,不過更為generic,實現自己的HandlerMethodArgumentResolver。
當前臺介面使用GET或POST方式提交資料時,資料編碼格式由請求頭的ContentType指定。分為以下幾種情況:
1. application/x-www-form-urlencoded,這種情況的資料@RequestParam、@ModelAttribute可以處理,@RequestBody也可以處理。
2. multipart/form-data,@RequestBody不能處理這種格式的資料。(form表單裡面有檔案上傳時,必須要指定enctype屬性值為multipart/form-data,意思是以二進位制流的形式傳輸檔案。)
3. application/json、application/xml等格式的資料,必須使用@RequestBody來處理。