AJAX api.js请求访问接口API需要用户名密码登录 身份签名认证(Basic Auth)

加了身份认证的API接口地址,访问API的时候,会弹出会话需要输入用户名和密码进行授权,输入正确后就可以获取返回的JSON数据

image.png

postman访问接口时效果如下:

image.png

 

那么如何通过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.eyJ1c2VyX25hbWUiOiJzZXJ2aWNldXNlcjEiLCJzdWNjZXNzIjp0cnVlLCJhdXRoX3VzZXIiOnsicGFzc3dvcmQiOiIkMmEkMTAkNzlkNGdrWFFqNm4wWWIyek9ySjhWLlQzNGFiY1hHeDF5bXNXQjBOejFHcVRQcUxBZGJ1NC4iLCJ1c2VybmFtZSI6InNlcnZpY2V1c2VyMSIsImF1dGhvcml0aWVzIjpbXSwiYWNjb3VudE5vbkV4cGlyZWQiOnRydWUsImFjY291bnROb25Mb2NrZWQiOnRydWUsImNyZWRlbnRpYWxzTm9uRXhwaXJlZCI6dHJ1ZSwiZW5hYmxlZCI6dHJ1ZSwiaWQiOjI0LCJ1c2VyY29kZSI6InNlcnZpY2V1c2VyMSIsIm5hbWUiOiLmnI3liqHkurrlkZgiLCJlbWFpbCI6IiIsInBob25lIjoiIiwidHlwZSI6IjMiLCJhdmF0YXIiOiJodHRwczovL2d3LmFsaXBheW9iamVjdHMuY29tL3p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MjgwLWFlNDdmNWQ3ZTkzOCIsImV4cCI6MTU4NTgxMzY3MywianRpIjoiYTJlNmMwYjAtNDMwMi00MjMyLThiMTQtMmExYjJmOTBmZDMxIiwiY2xpZW50X2lkIjoidGVzdF9jbGllbnQifQ.HsIr5Ljqn-YGf13GxeREQyalaPYHJXo8h1GkBFznCwg"
  },

postman请求截图:

image.png

本文由站长原创或收集,不代表本站立场,如若转载,请注明出处:http://www.swzhinan.com/post/259.html

共有 2 条评论

  1. avatar

    今日新闻

    文章非常好超喜欢

  2. avatar

    今日新闻

    文章非常好超喜欢

回复给

欢迎点评

联系我们

站长QQ:384827360

站长邮件:384827360@qq.com

工作时间:周一至周五,9:30-15:30,节假日休息

QR code