一,用postman摸擬js的JSON.stringify方式提交數據到接口:
我們這里看一個例子:用json方式提交用戶名和密碼后,
接口返回一個jwt的token字符串,
1,headers:
添加一項: Content-Type
取值為: application/json
如圖:
2,body標簽:
形式選擇:raw
格式選擇:JSON
如圖:
3,提交后可以看到結果:
說明:劉宏締的架構森林是一個專注架構的博客,地址:https://www.cnblogs.com/architectforest
對應的源碼可以訪問這里獲取: https://github.com/liuhongdi/
說明:作者:劉宏締 郵箱: 371125307@qq.com
二,用js實現json格式提交數據的例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用 jwt 登錄頁面</title> </head> <body> <div> <input type="text" id="userName" name="userName" value="" placeholder="username"> </div> <div> <input type="password" id="password" name="password" value="" placeholder="password"> </div> <div> <input type="button" id="btnSave" onclick="go_login()" value="登錄"> </div> <script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.js"></script> <script> //登錄 function go_login() { var username=$("#userName").val(); var password=$("#password").val(); if ($("#userName").val() == "") { alert('userName is empty'); $("#userName").focus(); return false; } if ($("#password").val() == "") { alert('password is empty'); $("#password").focus(); return false; } var postData = { "username":username , "password" : password } $.ajax({ cache: true, type: "POST", url: "/auth/authenticate", contentType: "application/json;charset=UTF-8", data:JSON.stringify(postData), dataType: "json", async: false, error: function (request) { console.log("Connection error"); }, success: function (data) { //save token console.log("data:"); console.log(data); if (data.code == 0) { //success alert("success:"+data.msg+";token:"+data.data.token); //save token localStorage.setItem("token",data.data.token); } else { //failed alert("failed:"+data.msg); } } }); }; </script> </body> </html>
關鍵的一行代碼是:
JSON.stringify(postData)