我想知道是否可以通过Javascript打开带有头部身份验证的浏览器?
调用API时,可以在Postman中为请求分配header。
但是我不知道期望浏览器能做同样的事情是否合理?
如果是,有没有使用验证头触发浏览器的例子?
谢谢
发布于 2020-07-03 03:47:22
假设您可以让浏览器加载一个运行JavaScript的页面,那么您就可以执行后续的API调用并向其附加头部。有多种框架可用,您也可以使用在大多数现代浏览器中运行良好的ES6 Fetch API。
参照取数:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
专门用于Fetch的Ref Header: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的一个非常基本的用例...您绝对应该阅读文档,将其设置为使用回调函数,而不是像上面的示例那样同步操作。但这应该会给你足够的细节让你继续前进
https://stackoverflow.com/questions/62707344
复制相似问题