我想知道是否可以通过Javascript标头身份验证来打开浏览器吗?
调用API时,我可以在Postman中为请求分配标头。
但是我找不到期望浏览器可以做同样的事情吗?
如果是,是否有使用身份验证标头触发浏览器的示例?
谢谢
答案 0 :(得分:0)
假设您可以让浏览器加载运行JavaScript的页面,然后可以执行后续API调用并将标头附加到它们。有多种可用的框架,或者您可以使用在大多数现代浏览器中都能正常运行的ES6 Fetch API。
参考获取文档: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
专门用于提取的引用标题: https://developer.mozilla.org/en-US/docs/Web/API/Headers
用户可以在其计算机上使用具有脚本来获取数据的本地文件...,或者您可以让用户点击不需要身份验证的端点,而仅充当承载具有API调用的页面的对象,他们的凭据,然后从受保护的端点请求经过身份验证的数据。
const myHeaders = new Headers();
myHeaders.set('Authentication', 'basic <insert base64 encoded basic auth string>');
const url = 'https://www.example.com/api/content';
const requestObj = {
method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default'
};
const myRequest = new Request(url, requestObj);
fetch(myRequest)
.then(response => response.json())
.then(jsonObj => {
//do stuff with whatever was returned in the json object
});
如果您使用的旧版浏览器不支持ES6版本或更高版本的JavaScript,则可以还原到旧版XMLHttpRequest。
参考XMLHttpRequest文档: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
var url = 'https://www.example.com/api/content';
var getRequest = new XMLHttpRequest();
getRequest.open('GET', url, false);
getRequest.setRequestHeader("Authentication", ''basic <insert base64 encoded basic auth string>'');
getRequest.send(null);
if (getRequest.status == 200){
var textData = req.responseText;
// do stuff with the response data
}
这是XMLHttpRequest的一个非常基本的用例...您一定应该阅读有关将其设置为使用回调函数的文档,而不是像上面的示例中那样进行同步操作。但这应该为您提供足够的详细信息以前进