#javascript #node.js #axios #github-api
#javascript #node.js #axios #github-api
Вопрос:
Я пытаюсь создать файл в репозитории github, прочитав текущую папку, в которой всего 3 файла. Что я заметил, что только один случайный файл успешно создается, а другой возвращает ошибку ниже
data: {
message: 'reference already exists',
documentation_url: 'https://docs.github.com/rest/reference/repos#create-or-update-file-contents'
}
хотя, когда я пробовал с postman, на удивление, ошибок вообще не было.
axios.put('https://api.github.com/repos/<owner>/<repo>/contents/index.php', {
// sha: hash,
committer: {
name: "TEST NAME",
email: "test@test.com"
},
content: <base64_data>,
message: "commit message",
branch: "master"
},
{
headers: {
Authorization: `Bearer <authKey>`,
ContentType: 'application/json'
}
}
);
Стек ошибок
Error: Request failed with status code 409
.........
at IncomingMessage.emit (events.js:228:7)
at endReadableNT (_stream_readable.js:1185:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21) {
config: {
url: 'https://api.github.com/repos/<owner>/<repo>/contents/index.php',
method: 'put',
data: '{"committer":{"name":"Something Name","email":"test@test.com"},"content":"<base64_Data>","message":"Commit Message","branch":"master"}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
Authorization: 'Bearer <auth-key>',
ContentType: 'application/json',
'User-Agent': 'axios/0.20.0',
'Content-Length': 372
},
params: {},
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus]
},
request: ClientRequest {
_events: [Object: null prototype] {
socket: [Function],
abort: [Function],
aborted: [Function],
connect: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.github.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.github.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 568,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'api.github.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.github.com',
_readableState: [ReadableState],
readable: true,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 568,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
_header: 'PUT /repos/<owner>/<repo>/contents/index.php HTTP/1.1rn'
'Accept: application/json, text/plain, */*rn'
'Content-Type: application/json;charset=utf-8rn'
'Authorization: Bearer <auth-key>rn'
'ContentType: application/jsonrn'
'User-Agent: axios/0.20.0rn'
'Content-Length: 372rn'
'Host: api.github.comrn'
'Connection: closern'
'rn',
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object]
},
socketPath: undefined,
method: 'PUT',
path: '/repos/<owner>/<repo>/contents/index.php',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 409,
statusMessage: 'Conflict',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl: 'https://api.github.com/repos/<owner>/<repo>/contents/index.php',
redirects: []
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: Writable {
_writableState: [WritableState],
writable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 372,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl: 'https://api.github.com/repos/<owner>/<repo>/contents/index.php'
},
[Symbol(kNeedDrain)]: false,
[Symbol(isCorked)]: false,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
authorization: [Array],
contenttype: [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array]
}
},
response: {
status: 409,
statusText: 'Conflict',
headers: {
date: 'Tue, 25 Aug 2020 17:18:29 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '136',
connection: 'close',
server: 'GitHub.com',
status: '409 Conflict',
'x-oauth-scopes': 'delete_repo, repo',
'x-accepted-oauth-scopes': '',
'x-github-media-type': 'github.v3',
'x-ratelimit-limit': '5000',
'x-ratelimit-remaining': '4984',
'x-ratelimit-reset': '1598377957',
'access-control-expose-headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset',
'access-control-allow-origin': '*',
'strict-transport-security': 'max-age=31536000; includeSubdomains; preload',
'x-frame-options': 'deny',
'x-content-type-options': 'nosniff',
'x-xss-protection': '1; mode=block',
'referrer-policy': 'origin-when-cross-origin, strict-origin-when-cross-origin',
'content-security-policy': "default-src 'none'",
vary: 'Accept-Encoding, Accept, X-Requested-With',
'x-github-request-id': 'F3BA:2E97:CF7EE3:116C291:5F4547E4'
},
config: {
url: 'https://api.github.com/repos/<owner>/<repo>/contents/index.php',
method: 'put',
data: '{"committer":{"name":"Something Name","email":"test@test.com"},"content":"<base64_Data>","message":"Commit Message","branch":"master"}',
headers: [Object],
params: {},
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
adapter: [Function: httpAdapter],
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus]
},
request: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header: 'PUT /repos/<owner>/<repo>/contents/index.php HTTP/1.1rn'
'Accept: application/json, text/plain, */*rn'
'Content-Type: application/json;charset=utf-8rn'
'Authorization: Bearer <auth-key>rn'
'ContentType: application/jsonrn'
'User-Agent: axios/0.20.0rn'
'Content-Length: 372rn'
'Host: api.github.comrn'
'Connection: closern'
'rn',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'PUT',
path: '/repos/<owner>/<repo>/contents/index.php',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Writable],
[Symbol(kNeedDrain)]: false,
[Symbol(isCorked)]: false,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: {
message: 'reference already exists',
documentation_url: 'https://docs.github.com/rest/reference/repos#create-or-update-file-contents'
}
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
Я использую nodejs, axios. Спасибо.
Комментарии:
1. Не очень уверен, но, похоже, ваш URL указывает на index.php можете ли вы перепроверить URL, используемый в Postman, а также с Postman, чтобы все 3 файла были загружены?
2. Да, все три файла загружаются без ошибок. и index.php это переменная path, а не фактический URL. /репозитории/{владелец}/{репозиторий}/содержимое/{путь}
3. Я говорю о {path} части URL в последнем комментарии, (я знаю index.php не является URL) можете ли вы скопировать вставить рабочий URL из Postman в code и протестировать
4. то, что я использовал в postman, я поместил здесь, за исключением некоторой личной информации. пожалуйста, скажите мне, что вам конкретно нужно
5. Кажется, все исправлено, мне было интересно, есть ли какая-либо опечатка при нажатии из Postman и из code, но, похоже, вы перепроверили это.
Ответ №1:
Я совершенно уверен, что это связано с тем, что вы не ожидаете завершения запроса, и это вызывает проблемы в репозитории.
Вы можете решить эту проблему с помощью асинхронной функции и ожидания запросов:
const axios = require('axios');
async function main() {
for (let i = 0; i < 5; i ) {
try {
const response = await axios.put('https://api.github.com/repos/<owner>/<repo>/contents/index.php', {
committer: {
name: "TEST NAME",
email: "test@test.com"
},
content: "SSBhbSB0cnlpbmcgdG8gaGVscCB5b3Uh",
message: "commit message",
branch: "master"
}, {
headers: {
Authorization: 'Bearer <token>',
ContentType: 'application/json'
}
});
console.log(response.data);
}
catch (e) {
console.error(e.response.data);
}
}
}
main();
Я надеюсь, что это помогло
Комментарии:
1. работает ли это с вашей стороны? потому что мой Axios тоже находится в режиме ожидания и время ожидания составляет 5 секунд. Я поделюсь своим кодом завтра.
2. @sp_kolinfure Да, это работает, но, конечно, я получаю запрос Invladid. ошибка «sha» не была определена, поскольку файл уже существует. Я все еще не мог найти ошибку ‘ссылка уже существует’, но я получил ‘is в ‘sha’, но ожидал ‘othersha», если я не ожидал обещаний в цикле.
3. Пожалуйста, создайте сценарий, в котором создайте репозиторий и попробуйте отправить два файла index.php и readme.md с соответствующим именем. вам не нужен sha при создании, верно. а затем проверьте, что произойдет.
4. Я не знаю, случилось ли что-то с главой ветки.
5. Я думаю, что время не является проблемой. Я использую 30-секундное время ожидания. первый запрос не удался, а второй запрос выполнен успешно. Я устал.