AJAX api.js请求访问接口API需要用户名密码登录 身份签名认证(Basic Auth)
加了身份认证的API接口地址,访问API的时候,会弹出会话需要输入用户名和密码进行授权,输入正确后就可以获取返回的JSON数据
用postman访问接口时效果如下:
那么如何通过AJAX实现,请求api地址,用户名和密码是如何传到后台去认证的?
在$.ajax里面设置headers参数
headers: { "Authorization": "Basic " + b64EncodeUnicode(USERNAME + ":" + PASSWORD) },
例如:
api.ajax({ url :url, method : 'post', cache : false, headers: { "Authorization": "Basic " + b64EncodeUnicode(USERNAME + ":" + PASSWORD) }, data : { values: { grant_type:'password', username: 'serviceuser1', password:'admin_2' } } }, function(ret, err) { log(ret); });
function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); })); }
。如果要传返回的token,需要在headers里设置
headers: { "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJzZXJ2aWNldXNlcjEiLCJzdWNjZXNzIjp0cnVlLCJhdXRoX3VzZXIiOnsicGFzc3dvcmQiOiIkMmEkMTAkNzlkNGdrWFFqNm4wWWIyek9ySjhWLlQzNGFiY1hHeDF5bXNXQjBOejFHcVRQcUxBZGJ1NC4iLCJ1c2VybmFtZSI6InNlcnZpY2V1c2VyMSIsImF1dGhvcml0aWVzIjpbXSwiYWNjb3VudE5vbkV4cGlyZWQiOnRydWUsImFjY291bnROb25Mb2NrZWQiOnRydWUsImNyZWRlbnRpYWxzTm9uRXhwaXJlZCI6dHJ1ZSwiZW5hYmxlZCI6dHJ1ZSwiaWQiOjI0LCJ1c2VyY29kZSI6InNlcnZpY2V1c2VyMSIsIm5hbWUiOiLmnI3liqHkurrlkZgiLCJlbWFpbCI6IiIsInBob25lIjoiIiwidHlwZSI6IjMiLCJhdmF0YXIiOiJodHRwczovL2d3LmFsaXBheW9iamVjdHMuY29tL3pvcy9ybXNwb3J0YWwvQmlhemZhbnhtYW1OUm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TU4NTgxMzY3MywianRpIjoiYTJlNmMwYjAtNDMwMi00MjMyLThiMTQtMmExYjJmOTBmZDMxIiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.HsIr5Ljqn-YGf13GxeREQyalaPYHJXo8h1GkBFznCwg" },
postman请求截图:
本文原创,转载必追究版权。