javascript - Github API“参考已经存在/StatusCode:409”创建或更新文件内容
问题描述
我正在尝试通过读取只有 3 个文件的当前文件夹在 github repo 中创建文件。我注意到只有一个随机文件成功创建,其他返回错误
data: {
message: 'reference already exists',
documentation_url: 'https://docs.github.com/rest/reference/repos#create-or-update-file-contents'
}
虽然当我尝试使用邮递员时,令人惊讶的是根本没有错误。
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.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json;charset=utf-8\r\n' +
'Authorization: Bearer <auth-key>\r\n' +
'ContentType: application/json\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Content-Length: 372\r\n' +
'Host: api.github.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_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.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json;charset=utf-8\r\n' +
'Authorization: Bearer <auth-key>\r\n' +
'ContentType: application/json\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Content-Length: 372\r\n' +
'Host: api.github.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_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。谢谢你。
解决方案
我很确定这是因为您不等待请求完成,这会导致存储库出现问题。
您可以通过使用异步函数并等待请求来解决此问题:
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();
我希望这有帮助
推荐阅读
- g1ant - 为什么在构建插件时会出现这么多错误?
- google-bigquery - Google Data Studio 中的直方图和分布
- python - Python websockets客户端保持连接打开
- jquery - 将 REST API 响应写入 HTML 表
- ruby-on-rails - Rails 中的记录数如何影响查询性能?
- laravel - 根据数组查看值
- quantum-computing - 2 纠缠量子比特为所有状态提供 25 %
- biztalk - 将多个源结构映射到 BizTalk 中的单个循环目标结构
- elasticsearch - ORDER BY IN 值列表位置
- mysql - 从 MySQL 中 3 列的每个组合中选择前 2 名得分者