问题描述
我想使用只读的访问令牌来做三件事,以便网页用户无需提供Gitlab身份验证。我必须使用标头中的访问令牌提交GET请求,并且还没有弄清楚如何使用Javascript处理响应。
我的代码
var myHeader = new Headers();
myHeader.append("PRIVATE-TOKEN",accesstoken);
var myInit = {
method: 'GET',headers: myHeader
};
var myRequest = new Request(artifactPath,myInit);
// response?
文档
Guidance provided代表1和2:
GET /projects/:id/jobs/artifacts/:ref_name/raw/*artifact_path?job=name
curl --location --header "PRIVATE-TOKEN: <your_access_token>"
"https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/master/raw/some/release/file.pdf?job=pdf"
Guidance provided for 3:
GET /projects/:id/jobs/artifacts/:ref_name/download?job=name
curl --header "PRIVATE-TOKEN: <your_access_token>"
"https://gitlab.example.com/api/v4/projects/1/jobs/artifacts/master/download?job=test"
我对Ajax会有所帮助,这是我从未使用过的印象。所有可行的简单性将不胜感激!
解决方法
通过两个浏览器API,原生JavaScript可以使用AJAX。
您有XMLHttpRequest(较旧,更兼容,但是语法很丑):
var xhr = new XMLHttpRequest();
xhr.open('GET','https://example.com/path/to/get');
xhr.setRequestHeader('Your-Header-Name','Value');
xhr.onload = function() {
// What this is depends on what kind of data the endpoint returned
console.log(xhr.response);
}
xhr.send();
现代JavaScript用户通常更喜欢Fetch API(更新,兼容性差,简洁的语法):
// Note this will contain some ES6 stuff,such as Promises
fetch('https://example.com/path/to/get',{
// This is optional: method is GET by default
method: 'GET',headers: {
'Your-Header-Name': 'Value'
}
}).then(res =>
// You can do res.arrayBuffer(),.text(),but assuming the response is JSON...
res.json()
).then(console.log);
我通常使用fetch
,但是您使用的方法主要是个人喜好。