我正在尝试使用AWS客户端网关API从节点js执行AWS REST API。
代码如下:
var apigClientFactory = require('aws-api-gateway-client').default;
let awsbody = JSON.parse(process.argv[2].split('\\').join('') || '{}');
// Loggin to confirm Input
var apigClient = apigClientFactory.newClient({
invokeUrl: awsbody.endPoint, // REQUIRED
accessKey: awsbody.awsAccessKey, // REQUIRED
secretKey: awsbody.awsSecreteKey, // REQUIRED
region: awsbody.awsRegion, // REQUIRED: The region where the API is deployed.
retryCondition: (err) => { // OPTIONAL: Callback to further control if request should be retried. Uses axon-retry plugin.
return err.response && err.response.status === 500;
}
});
var pathParams = awsbody.awsPathParams;
// Template syntax follows url-template https://www.npmjs.com/package/url-template
var pathTemplate = awsbody.awsPathTemplate; // '/api/v1/sites'
var method = awsbody.method; // 'POST';
var additionalParams = { queryParams: awsbody.awsAdditionalParams };
//var additionalParams = {};
var body = awsbody.requestBody;
var output = {};
apigClient.invokeApi(pathParams, pathTemplate, method, additionalParams, body)
.then(function(result) {
// return JSON.parse(result.data);
output.state = result.response.data,
output.header = result.response.headers;
return output
// console.log(result.response.headers)
}).catch(function(result) {
//console.log(result)
// console.log(result.response.data)
// console.log(result.response.status + " - " +
result.response.statusText)
output.state = result.response.data,
output.responsecode = result.response.status,
output.responsetext = result.response.statusText;
return output
});
后执行低于错误:
错误消息:(节点:3424)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ data” 在C:\ Servicenow \ nodejs \ awsInvokeRestapi.js:63:40 在process.internalTickCallback(内部/进程/next_tick.js:77:7) (节点:3424)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。引发此错误的原因可能是抛出了一个没有catch块的异步函数,或者是拒绝了一个.catch()无法处理的承诺。 (拒绝ID:2) (节点:3424)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。将来,未处理的承诺拒绝将以非零退出代码终止Node.js进程。
但是,如果我只是返回结果,则输出没有任何问题。但是在这里,我试图从结果中仅读取必要的信息。
这是整个结果:我只需要数据对象。
{ Error: Request failed with status code 404
at createError (C:\Users\kp250041\desktop\Myfiles\node_modules\aws-api-gateway-client\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\kp250041\desktop\Myfiles\node_modules\aws-api-gateway-client\node_modules\axios\lib\core\settle.js:18:12)
at IncomingMessage.handleStreamEnd (C:\Users\kp250041\desktop\Myfiles\node_modules\aws-api-gateway-client\node_modules\axios\lib\adapters\http.js:201:11)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
config:
{ adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ Accept: 'application/json',
'x-amz-date': '20190122T211036Z',
Authorization:
'AWS4-HMAC-SHA256 Credential=AKIAJ4Y5DGRDNBQ2HBYA/20190122/us-west-2/execute-api/aws4_request, SignedHeaders=accept;host;x-amz-date, Signature=dfa8326d867efde822f2974ab7b197a7f8fd26189a09e558399cb8339cb249f1', 'Content-Type': 'application/json',
'User-Agent': 'axios/0.18.0' },
method: 'delete',
data: undefined,
url:
'https://vs2i50xvo4.execute-api.us-west-2.amazonaws.com/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D' },
request:
ClientRequest {
_events:
{ socket: [Function],
abort: [Function],
aborted: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish] },
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'vs2i50xvo4.execute-api.us-west-2.amazonaws.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'vs2i50xvo4.execute-api.us-west-2.amazonaws.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)]: 6,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: 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: 'vs2i50xvo4.execute-api.us-west-2.amazonaws.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: 'vs2i50xvo4.execute-api.us-west-2.amazonaws.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)]: 6,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
_header:
'DELETE /qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D HTTP/1.1\r\nAccept: application/json\r\nx-amz-date: 20190122T211036Z\r\nAuthorization: AWS4-HMAC-SHA256 Credential=AKIAJ4Y5DGRDNBQ2HBYA/20190122/us-west-2/execute-api/aws4_request, SignedHeaders=accept;host;x-amz-date, Signature=dfa8326d867efde822f2974ab7b197a7f8fd26189a09e558399cb8339cb249f1\r\nContent-Type: application/json\r\nUser-Agent: axios/0.18.0\r\nHost: vs2i50xvo4.execute-api.us-west-2.amazonaws.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
_events: [Object],
_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,
timeout: undefined,
method: 'DELETE',
path:
'/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D',
_ended: true,
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_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: 404,
statusMessage: 'Not Found',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl:
'https://vs2i50xvo4.execute-api.us-west-2.amazonaws.com/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D',
redirects: [] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl:
'https://vs2i50xvo4.execute-api.us-west-2.amazonaws.com/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D' },
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
{ accept: [Array],
'x-amz-date': [Array],
authorization: [Array],
'content-type': [Array],
'user-agent': [Array],
host: [Array] } },
response:
{ status: 404,
statusText: 'Not Found',
headers:
{ 'content-type': 'application/json',
'content-length': '53',
connection: 'close',
date: 'Tue, 22 Jan 2019 21:10:37 GMT',
'x-amzn-requestid': '2a1ca05d-1e8a-11e9-8b27-cd6ea47769e0',
'x-amz-apigw-id': 'T7IAEEB2PHcFWHA=',
'x-amzn-trace-id': 'Root=1-5c4786cd-94386d24d094bb8aa6614efa;Sampled=0',
'x-cache': 'Error from cloudfront',
via:
'1.1 4a283201d995829e522a4b36763be15d.cloudfront.net (CloudFront)',
'x-amz-cf-id': 'xqR_nC0-wVzDYVLJUEaqcej_I2jIYu3DurnjwtQ1WHwtm9Vl_D1USw==' },
config:
{ adapter: [Function: httpAdapter],
transformRequest: [Object],
transformResponse: [Object],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'delete',
data: undefined,
url:
'https://vs2i50xvo4.execute-api.us-west-2.amazonaws.com/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D' },
request:
ClientRequest {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header:
'DELETE /qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D HTTP/1.1\r\nAccept: application/json\r\nx-amz-date: 20190122T211036Z\r\nAuthorization: AWS4-HMAC-SHA256 Credential=AKIAJ4Y5DGRDNBQ2HBYA/20190122/us-west-2/execute-api/aws4_request, SignedHeaders=accept;host;x-amz-date, Signature=dfa8326d867efde822f2974ab7b197a7f8fd26189a09e558399cb8339cb249f1\r\nContent-Type: application/json\r\nUser-Agent: axios/0.18.0\r\nHost: vs2i50xvo4.execute-api.us-west-2.amazonaws.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'DELETE',
path:
'/qa/transit-connectivity/api/v1/sites/TDCLOUDAMTD05?change_request=%5Bobject%20Object%5D',
_ended: true,
res: [IncomingMessage],
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Writable],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
data: { status: 'failed', message: 'resource not found' } } }