我的理解emulateJSON做用 與java後臺接口參數的關係

Vue請求:javascript

this.$http.post("/test", {
    'name': '弟中弟',
    'phone': '186220666666',
    'age': 18
}).then((respones) => {
    console.log(respones.body)
});
複製代碼

在沒有設置參數emulateJSON:true時 後臺接口只能經過@RequestBody註解將請求發來的json字符串參數轉換成對應的JavaBean, 最終發送的請求是(無關的請求頭在本文中都省略掉了):java

POST http://www.example.com HTTP/1.1
    Content-Type: application/json;charset=utf-8
    {"name":"弟中弟","phone":"186220666666","age"=18}
複製代碼
@Data
public class Person {
    private String name;
    private String phone;
    private Integer age;
}
複製代碼

接口:json

@PostMapping("/test")
    public String test(@RequestBody Person Person){
       //TODO
    }
複製代碼

解釋一下:若是Web服務器沒法處理編碼爲application/json的請求,你能夠啓用emulateJSON選項。服務器

啓用該選項後,請求會以application/x-www-form-urlencoded做爲Content-Type,就像普通的HTML表單同樣。app

若是添加上此參數,後臺接口能夠更靈活性的接收參數

this.$http.post("/test", {
    'name': '弟中弟',
    'phone': '186220666666',
    'age': 18
},{emulateJSON:true}).then((respones) => {
    console.log(respones.body)
});
複製代碼

若是沒有使用@RequestBody 註解咱們同樣能夠接收參數轉換成JavaBean,由於沒有@RequestBody註解咱們沒法解析,可是emulateJSON:true就會是數據使用application/x-www-form-urlencoded的方式提交。 請求相似於下面這樣(無關的請求頭在本文中都省略掉了)post

POST http://www.example.com HTTP/1.1
   Content-Type: application/x-www-form-urlencoded;charset=utf-8
   name=弟中弟&phone=186220666666&age=18   這裏不該該是明文我就不轉換了
複製代碼
@PostMapping("/test")
    public String test(Person Person){
       //TODO
    }
複製代碼

因此你也能夠在main.js中全局定義這個參數

Vue.http.options.emulateJSON = true;學習


這是本人今天在學習中寫接口遇到關於不理解emulateJSON做用,本身琢磨的 也不知道對不對在我看來就是提升了接口參數的靈活性,也不知道分析的對不對,有錯請原諒, 但願各位大佬指點一下萌新ui

相關文章
相關標籤/搜索