一,用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)