我在使用
https.get
功能设置标题时遇到问题。
我需要使用 gitlab API 访问一个文件,该文件需要这样的标头:
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects"
如何设置这样的标题?
我已经试过了:
const options = {
hostname: 'gitlab.example.com',
path: '/api/v4/projects',
headers: {
"PRIVATE-TOKEN": "<your_access_token>"
}
}
https.get(options, (resp) => {
...
})
或
const options = {
hostname: 'gitlab.example.com',
path: '/api/v4/v4/projects',
headers: "PRIVATE-TOKEN: <your_access_token>"
}
https.get(options, (resp) => {
...
})
或
const options = {
hostname: 'gitlab.example.com',
path: '/api/v4/projects',
headers: {
"PRIVATE-TOKEN: <your_access_token>":""
}
}
https.get(options, (resp) => {
...
})
在这两种情况下,响应不正确
1。使用 HTTP.get 请求
在 Node.js 中,当您使用 https.get 函数时,您应该为 headers 字段提供一个对象,其中每个 header 字段都是一个单独的键值对。
示例:
const https = require('https');
const options = {
hostname: 'gitlab.example.com',
path: '/api/v4/projects',
headers: {
'PRIVATE-TOKEN': '<your_access_token>'
}
}
https.get(options, (resp) => {
var result = ''
resp.on('data', function (chunk) {
result += chunk;
});
resp.on('end', function () {
console.log(result);
});
});
2。使用 Axios
您可以使用 Axios 在 Node.js 中发出 HTTP 请求,包括使用自定义标头向 GitLab API 发出请求。
const axios = require('axios');
const gitlabUrl = 'https://gitlab.example.com/api/v4/projects';
const accessToken = '<your_access_token>';
const config = {
headers: {
'PRIVATE-TOKEN': accessToken
}
};
注意:请记住将 '