Unable to post to DynamoDB using axios - javascript

So I'm currently trying to post data to my DynamoDB using API Gateway. When I test it out, it comes back as a 200 status - but my DynamoDB is never updated.
Here is my axios post request:
axios.post('https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users', {
email: "test#gmail.com",
salt: "123",
sha512: "123"
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
Here is my Lambda function that I hit with that API gateway:
const AWS = require('aws-sdk');
const dynamoDb = new AWS.DynamoDB.DocumentClient({ region: 'us-west-1' });
exports.handler = async function(event, ctx, callback) {
var params = {
Item: {
email: event.email,
salt: event.salt,
sha512: event.sha512
},
TableName: 'users'
}
try {
const data = await dynamoDb.put(params).promise()
console.log({ statusCode: 200, body: { params, data }})
} catch (err) {
console.log(err)
}
}
And this is what gets logged after my axios call:
{ status: 200,
statusText: 'OK',
headers:
{ date: 'Thu, 28 Feb 2019 02:41:01 GMT',
'content-type': 'application/json',
'content-length': '4',
connection: 'close',
'x-amzn-requestid': '49249c4f-3b02-11e9-af6d-819f17575656',
'x-amz-apigw-id': 'VyiJmFI6SK4FgYQ=',
'x-amzn-trace-id': 'Root=1-5c774a3d-2fc47364e1170574a6f083c4;Sampled=0' },
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, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.18.0',
'Content-Length': 54 },
method: 'post',
url:
'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users',
data: '{"email":"test#gmail.com","salt":"123","sha512":"123"}' },
request:
ClientRequest {
domain: null,
_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: 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: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
_readableState: [ReadableState],
readable: true,
domain: null,
_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)]: 7,
[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: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: [TLSWrap],
_parent: null,
_host: '1eugzswetg.execute-api.us-west-1.amazonaws.com',
_readableState: [ReadableState],
readable: true,
domain: null,
_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)]: 7,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object] },
_header:
'POST /beta/users HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 54\r\nHost: 1eugzswetg.execute-api.us-west-1.amazonaws.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
domain: null,
_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: 'POST',
path: '/beta/users',
_ended: true,
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
domain: null,
_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: 200,
statusMessage: 'OK',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular],
responseUrl:
'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users',
redirects: [] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable:
Writable {
_writableState: [WritableState],
writable: true,
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 54,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular],
_currentUrl:
'https://1eugzswetg.execute-api.us-west-1.amazonaws.com/beta/users' },
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
{ accept: [Array],
'content-type': [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array] } },
data: null }
Any idea why my DynamoDB isn't getting updated? When I test it within the API Gateway console it works. Here is a screenshot of what happens when I test it within the API Gateway console

If its working from API gateway console then its a client issue, or latest version in not deployed to api gateway stage?

Tips:
You could try amazon cloudwatch service, and looking what it is happen inside the function.
Are you sure that your user (IAM) has permission? Access Keys for IAM Users
You must return anything in this function something like that:
export async function ping(event, context) {
...
...
...
return Promise((resolve,reject) => {
return resolve({
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": null,
"isBase64Encoded": false
})
})
}
I prepare for you a basic example (working) putItem implementation:
See code
git clone
npm install
npm run deploy
magic!!
files that you must looking:
package.json (all dependencies installed) i used serverless framework
serverless.yml (all configurations for you deploy) also i'm creating a dynamodb table resource your name is "TableTest", each deploy i'm removing all resource and creating again.
important: You must have AWS credentials file in your system. ex: ~/.aws/credentials
Good luck!

Related

Looping through URLs with axios.get

I have an object full of museum names:
const museumNamesForScraping = [
"Boston Children's Museum (e-ticket)",
"Boston Harbor Islands",
"DCR - Mass Dept of Conservation and Recreation",
"Hale Reservation",
"Harvard Museums of Science and Culture",
"ICA - Institute of Contemporary Art",
"Isabella Stewart Gardner Museum (promo code)",
"John F Kennedy Library and Museum",
"Larz Anderson Auto Museum",
"Mass Audubon Wildlife Sanctuary",
"Museum of Fine Arts (e-voucher)",
"Museum of Science (e-voucher)",
"New England Aquarium (e-coupon)",
"Old South Meeting House",
"Old Sturbridge Village",
"Peabody Essex Museum",
"Trustees GO Pass",
"USS Constitution Museum",
"Zoo New England"
];
I am trying to add each of the above museum names onto a URL to scrape data from each page like such:
museumNamesForScraping.forEach((museumName) => {
axios.get('https://www.eventkeeper.com/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=' + museumName)
.then(res => {
const $ = cheerio.load(res.data);
let title = $("title").text();
console.log(title);
}
)
.catch(err => {
console.log(err);
}
);
});
Strangely, 3 or so out of the total list of museum names work each time I run the code with the rest erroring with the following details:
[AxiosError: Request failed with status code 500] {
code: 'ERR_BAD_RESPONSE',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.27.2'
},
method: 'get',
url: 'https://www.eventkeeper.com/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old South Meeting House',
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
_defaultKeepAlive: true,
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,
secureConnecting: false,
_SNICallback: null,
servername: 'www.eventkeeper.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'www.eventkeeper.com',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 930031,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'GET /mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: www.eventkeeper.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 32,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 4,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 500,
statusMessage: 'Variable CHARLIE_SETTING_NONEXISTENT_VAR_TO_BREAK_APP_TO_STOP_LOOPING is undefined.',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://www.eventkeeper.com/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'www.eventkeeper.com',
protocol: 'https:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://www.eventkeeper.com/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'user-agent': [Array],
host: [Array]
}
},
response: {
status: 500,
statusText: 'Variable CHARLIE_SETTING_NONEXISTENT_VAR_TO_BREAK_APP_TO_STOP_LOOPING is undefined.',
headers: {
'content-type': 'text/html',
'retry-after': '5',
server: 'Microsoft-IIS/7.5',
'set-cookie': [Array],
'server-error': 'true',
'x-powered-by': 'ASP.NET',
date: 'Thu, 11 Aug 2022 03:05:07 GMT',
connection: 'close',
'content-length': '1208'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
method: 'get',
url: 'https://www.eventkeeper.com/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old South Meeting House',
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
_header: 'GET /mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: www.eventkeeper.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/mars/tkflex.cfm?curOrg=BOSTON&curNumDays=1&curKey1=Old%20South%20Meeting%20House',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'www.eventkeeper.com',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\r\n' +
'<html xmlns="http://www.w3.org/1999/xhtml">\r\n' +
'<head>\r\n' +
'<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>\r\n' +
'<title>500 - Internal server error.</title>\r\n' +
'<style type="text/css">\r\n' +
'<!--\r\n' +
'body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}\r\n' +
'fieldset{padding:0 15px 10px 15px;} \r\n' +
'h1{font-size:2.4em;margin:0;color:#FFF;}\r\n' +
'h2{font-size:1.7em;margin:0;color:#CC0000;} \r\n' +
'h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} \r\n' +
'#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;\r\n' +
'background-color:#555555;}\r\n' +
'#content{margin:0 0 0 2%;position:relative;}\r\n' +
'.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}\r\n' +
'-->\r\n' +
'</style>\r\n' +
'</head>\r\n' +
'<body>\r\n' +
'<div id="header"><h1>Server Error</h1></div>\r\n' +
'<div id="content">\r\n' +
' <div class="content-container"><fieldset>\r\n' +
' <h2>500 - Internal server error.</h2>\r\n' +
' <h3>There is a problem with the resource you are looking for, and it cannot be displayed.</h3>\r\n' +
' </fieldset></div>\r\n' +
'</div>\r\n' +
'</body>\r\n' +
'</html>\r\n'
}
}
I haven't been able to find much on the error's statusText:
statusText: 'Variable CHARLIE_SETTING_NONEXISTENT_VAR_TO_BREAK_APP_TO_STOP_LOOPING is undefined.',
Any help on how to troubleshoot this error would be greatly appreciated.
Thanks!

Spotify Web API with Axios returns error 500 randomly

I have an array of songs, structure is the following, FYI there are around 35 items in the array in the case I'm doing
songs [
{
song_id: '09wkyp6dMAo5JakEj49R0M',
artist_id: '5EmEZjq8eHEC6qFnT63Lza',
},
{
song_id: '2GaEPiwjVhSMrhX0zC5zJL',
artist_name: '5EmEZjq8eHEC6qFnT63Lza'
}
]
I'm doing a for loop through each song
const assignSongsToPlaylists = async () => {
for (let s of songs) {
//getting groupID from my MongoDB
const { connectedGroupId } = await Artist.findOne({
artistSpotifyId: s.artist_id,
})
//needed the groupID from above in here, to find to which playlist should I put the song in
const { connectedPlaylistId } = await Group.findOne({
_id: connectedGroupId,
})
//putting the song into a specific playlist
const response = await axios.post(
`/playlists/${connectedPlaylistId}/tracks?uris=spotify%3Atrack%3A${s.song_id}`,
)
}
}
const response = await assignSongsToPlaylists()
The issue here is, that sometimes the action is successfull, meaning that all songs from the aforementioned array are successfully added to single or multiple playlists in my Spotify account, all axios post requests are successfull.
However, sometimes the axios post fails after couple of songs(it failed after 5 songs, sometimes after 25 songs, tends to fail randomly) and results in the following error:
[AxiosError: Request failed with status code 500] {
code: 'ERR_BAD_RESPONSE',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [Function: httpAdapter],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function] },
validateStatus: [Function: validateStatus],
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'Bearer BQDRCNSvjVhblc90InW1yFRUql0DDfjvjYTahkyrlvSwLr254eBa2NKv2ci4wUPKc3u9iL5ebDfVijHbyrs0aBnB1yhTRswaC_X9sqrquLFHXLebcwO4JnKRb4vJyFoyEd2950lpTkaKQz1egqubs-ciM4gIq9QzWDCSi7INBKIb6kscJrJrPXrlC_gTp0gyL-VUBNrqoalsPhjmZd9ehwJumbkXNX5v0DWBmSXCcUuflap3G_LCYb_CpT',
'User-Agent': 'axios/0.27.2'
},
baseURL: 'https://api.spotify.com/v1',
method: 'post',
url: '/playlists/0nK2ra8DA5ZLB7dFcCgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'api.spotify.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'api.spotify.com',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 1494,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'POST /v1/playlists/1nK2ra8Zw5ZLf7dFcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65 HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'Authorization: Bearer BQDRCNSvjVhblc90InW1yFRUql0DDfjvjYTahkyrlvSwLr254eBa2NKv2ci4wUPKc3u9iL5ebDfVijHbyrs0aBnB1yhTRswaC_X9sqrquLFHXLebcwO4JnKRb4vJyFoyEd2950lpTkaKQz1egqubs-ciM4gIq9QzWDCSi7INBKIb6kscJrJrPXrlC_gTp0gyL-VUBNrqoalsPhjmZd9ehwJumbkXNX5v0DWBmSXCcUuflap3G_LCYb_CpT\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: api.spotify.com\r\n' +
'Connection: close\r\n' +
'Content-Length: 0\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v1/playlists/1nK2ra8Zd5ZWf7dFcXgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 4,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 500,
statusMessage: 'Internal Server Error',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://api.spotify.com/v1/playlists/4fK2ra8Zd5WLf72FcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 34,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.spotify.com',
protocol: 'https:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://api.spotify.com/v1/playlists/3nK2ra84d5ZLf7GFcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
authorization: [Array],
'user-agent': [Array],
host: [Array]
}
},
response: {
status: 500,
statusText: 'Internal Server Error',
headers: {
'content-type': 'application/json; charset=utf-8',
'cache-control': 'private, max-age=0',
'x-robots-tag': 'noindex, nofollow',
'access-control-allow-origin': '*',
'access-control-allow-headers': 'Accept, App-Platform, Authorization, Content-Type, Origin, Retry-After, Spotify-App-Version, X-Cloud-Trace-Context, client-token, content-access-token',
'access-control-allow-methods': 'GET, POST, OPTIONS, PUT, DELETE, PATCH',
'access-control-allow-credentials': 'true',
'access-control-max-age': '604800',
'content-length': '73',
'strict-transport-security': 'max-age=31536000',
'x-content-type-options': 'nosniff',
vary: 'Accept-Encoding',
date: 'Sun, 07 Aug 2022 14:02:48 GMT',
server: 'envoy',
via: 'HTTP/2 edgeproxy, 1.1 google',
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
connection: 'close'
},
config: {
transitional: [Object],
adapter: [Function: httpAdapter],
transformRequest: [Array],
transformResponse: [Array],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: [Object],
validateStatus: [Function: validateStatus],
headers: [Object],
baseURL: 'https://api.spotify.com/v1',
method: 'post',
url: '/playlists/0nK2ra3Fd5ZLf7GFcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
data: undefined
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: [TLSSocket],
_header: 'POST /v1/playlists/0DF2ra1Zd5ZGG7dFcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65 HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'Content-Type: application/json\r\n' +
'Authorization: Bearer BQDRCNSvjVhblc90InW1yFRUql0DDfjvjYTahkyrlvSwLr254eBa2NKv2ci4wUPKc3u9iL5ebDfVijHbyrs0aBnB1yhTRswaC_X9sqrquLFHXLebcwO4JnKRb4vJyFoyEd2950lpTkaKQz1egqubs-ciM4gIq9QzWDCSi7INBKIb6kscJrJrPXrlC_gTp0gyL-VUBNrqoalsPhjmZd9ehwJumbkXNX5v0DWBmSXCcUuflap3G_LCYb_CpT\r\n' +
'User-Agent: axios/0.27.2\r\n' +
'Host: api.spotify.com\r\n' +
'Connection: close\r\n' +
'Content-Length: 0\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/v1/playlists/0nK2rh45d5hLf7dFcMgRMw/tracks?uris=spotify%3Atrack%3A0cjYF44Vkl5UK2xYf6KM65',
_ended: true,
res: [IncomingMessage],
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'api.spotify.com',
protocol: 'https:',
_redirectable: [Writable],
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype]
},
data: { error: [Object] }
}
}
Any idea what could cause this behavior?
Fixed by sending multiple song IDs at once. Spotify seems to be allowing around 90 IDs in one request. I sent them one by one.

Axios is adding localhost path before url in node.js

I have a problem with Axios.
Axios is adding a localhost path before the URL in node.js.
Here is my code:
import VerifyCodes from '../../../model/DatabaseModel/VerifyCodes';
import axios from 'axios';
import qs from 'qs';
const apiUrl = 'https://api.ghasedak.io/v2/verification/send/simple';
let axiosConfig = {
method: 'post',
url: apiUrl,
headers: {
apikey: 'someNumbers',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: null,
};
let additionalBodyData = {
template: 'test',
type: '1',
};
export const generateAuthenticationCode = (receptor) =>
new Promise(async (resolve, reject) => {
let code =
Math.floor(Math.random() * (9999 - 1111 + 1)) + 1111;
axiosConfig.data = qs.stringify({
...additionalBodyData,
param1: String(code),
receptor,
});
await VerifyCodes.insertOrUpdateNewCode(receptor, code);
// #ts-ignore
axios(axiosConfig)
.catch(reject)
.then(() => resolve(code));
});
And here is my error:
{ Error: connect ECONNREFUSED 127.0.0.1:34773
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 34773,
config:
{ url: 'https://api.ghasedak.io/v2/verification/send/simple',
method: 'post',
data: 'template=test&type=1&param1=2549&receptor=0856',
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/x-www-form-urlencoded',
apikey: 'apiKey',
'User-Agent': 'axios/0.21.0',
'Content-Length': 53,
host: 'api.ghasedak.io' },
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:
Writable {
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
_events:
[Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError] },
_eventsCount: 2,
_maxListeners: undefined,
_options:
{ maxRedirects: 21,
maxBodyLength: 10485760,
protocol: 'http:',
path: 'https://api.ghasedak.io/v2/verification/send/simple',
method: 'POST',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: '127.0.0.1',
port: '34773',
nativeProtocols: [Object],
pathname: 'https://api.ghasedak.io/v2/verification/send/simple' },
_ended: false,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 53,
_requestBodyBuffers: [ [Object] ],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest {
_events: [Object],
_eventsCount: 7,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
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: false,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header:
'POST https://api.ghasedak.io/v2/verification/send/simple HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/x-www-form-urlencoded\r\napikey: 3dac6bca51eed0a5f60d0fb3e5f9a230daf62e81aae3e018016f9bc37e4bf8c9\r\nUser-Agent: axios/0.21.0\r\nContent-Length: 53\r\nhost: api.ghasedak.io\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
insecureHTTPParser: undefined,
path: 'https://api.ghasedak.io/v2/verification/send/simple',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
_currentUrl:
'http://127.0.0.1:34773/https://api.ghasedak.io/v2/verification/send/simple' },
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON] }
As you can see Axios added http://127.0.0.1:34773/ to the URL and I am sure that I have not set the Axios default baseUrl in my project.
I have not idea why this is happening and do not know what to do!
Can anyone help me please?
I tried the same configuration as you,it's work well.
look like you want hide some important info, e.g. apikey.
They are shown in detail in the error message.

Using Axios to post a message in Microsoft Teams

UPDATED QUESTION 16-10-2020
I simplified the code so it doesn't contain an if statement anymore to run the postMessageToTeams function and I added the error response I receive in the catch. Hopefully this makes it easier to debug.
It works when I run the script from my Visual Studio terminal but it doesn't when running it from my cmder. So I reckon it has something to do with my cmder settings.
Goal
I'm running some automated tasks through testcafe and would like to be notified in Microsoft Teams when a certain task is done. To do so, I created a webhook in my channel and wanted to send a POST request to my webhook URL. However, when doing so, I receive a 405 error. When trying it out in Postman it does work with the same JSON data.
My code (I slightly altered the code from https://gist.github.com/johnsibly/806a7190fbdc4b439ed040f327e6e679 for this test)
const axios = require('axios'); // axios must be installed via npm i axios
const webhookURL = "https://outlook.office.com/webhook/xxxxx"; // this holds my webhook URL
postMessageToTeams();
async function postMessageToTeams(title, message) {
const card = {
"#type": "MessageCard",
"#context": "http://schema.org/extensions",
"themeColor": "0072C6",
"summary": "Summary description",
"sections": [
{
"activityTitle": "Testcafe",
"text": "Testcafe is talking to you"
}
]
};
try {
const response = await axios.post(webhookURL, card, {
headers: {
'content-type': 'application/vnd.microsoft.teams.card.o365connector',
'content-length': `${card.toString().length}`,
},
});
return `${response.status} - ${response.statusText}`;
} catch (err) {
console.log(err)
return err;
}
}
Error response
{
status: 405,
statusText: 'Method Not Allowed',
headers: {
'cache-control': 'no-cache',
pragma: 'no-cache',
allow: 'POST',
'content-length': '43',
'content-type': 'text/plain; charset=utf-8',
expires: '-1',
server: 'Microsoft-IIS/10.0',
'request-id': 'b565e1ec-79a2-4fc1-99e1-56e8caa98a48',
'strict-transport-security': 'max-age=31536000; includeSubDomains; preload',
'x-calculatedbetarget': 'AM0PR02MB5570.eurprd02.prod.outlook.com',
'x-backendhttpstatus': '405',
'x-aspnet-version': '4.0.30319',
'x-cafeserver': 'AM3PR07CA0145.EURPRD07.PROD.OUTLOOK.COM',
'x-beserver': 'AM0PR02MB5570',
'x-proxy-routingcorrectness': '1',
'x-proxy-backendserverstatus': '405',
'x-powered-by': 'ASP.NET',
'x-feserver': 'AM3PR07CA0145',
date: 'Fri, 16 Oct 2020 07:58:34 GMT',
connection: 'close'
},
config: {
url: 'https://outlook.office.com/webhook/xxxx',
method: 'post',
data: '{"#type":"MessageCard","#context":"http://schema.org/extensions","themeColor":"0072C6","summary":"Summary description","sections":[{"activityTitle":"Testcafe","text":"Testcafe is talking to you"}]}',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.20.0'
},
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: <ref *1> ClientRequest {
_events: [Object: null prototype] {
socket: [Function (anonymous)],
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
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: 'outlook.office.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 9,
connecting: false,
_hadError: false,
_parent: null,
_host: 'outlook.office.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 *1],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 15,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object]
},
_header: 'GET /webhook/xxxx HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Host: outlook.office.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
path: '/webhook/xxxx',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 405,
statusMessage: 'Method Not Allowed',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://outlook.office.com/webhook/xxxx',
redirects: [],
[Symbol(kCapture)]: false
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
_redirectable: Writable {
_writableState: [WritableState],
writable: true,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 1,
_redirects: [],
_requestBodyLength: 197,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://outlook.office.com/webhook/xxxx',
_isRedirect: true,
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'user-agent': [Array],
host: [Array]
}
},
data: 'Invalid webhook request - GET not supported'
}
If you'd need the entire error message in order to properly debug this, please let me know.
Postman
Body (raw) of POST request
{
"#type": "MessageCard",
"#context": "http://schema.org/extensions",
"themeColor": "0072C6",
"summary": "Summary description",
"sections": [
{
"activityTitle": "Testcafe",
"text": "Testcafe is talking to you"
}
]
}
Response
1, and the message is posted in my Teams channel
You should let axios handle the calculation of the payload length, and therefore remove this line:
'content-length': `${card.toString().length}`
Your resulting script from your post would look like:
const axios = require('axios'); // axios must be installed via npm i axios
const webhookURL = "https://outlook.office.com/webhook/xxxxx"; // this holds my webhook URL
postMessageToTeams();
async function postMessageToTeams(title, message) {
const card = {
"#type": "MessageCard",
"#context": "http://schema.org/extensions",
"themeColor": "0072C6",
"summary": "Summary description",
"sections": [
{
"activityTitle": "Testcafe",
"text": "Testcafe is talking to you"
}
]
};
try {
const response = await axios.post(webhookURL, card, {
headers: {
'content-type': 'application/vnd.microsoft.teams.card.o365connector'
},
});
return `${response.status} - ${response.statusText}`;
} catch (err) {
console.log(err)
return err;
}
}
Found this working for me.

Not able to fetch data inside node-cron schedule method

so I was trying to schedule an update in the database every night at 12, and I am able to run Cron jobs using my server, but I am not able to fetch data using Axios, I tried an external URL from a tutorial like "https://jsonplaceholder.typicode.com/posts/1" and the data comes, but when I use the url/routes I made to fetch data in the reactjs front end.. like this "http://localhost:9000/api/getAllDealHeader" and pass it as URL, it gives an error like
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:183:27) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
config: {
url: 'http://localhost:9000/api/getAllDealHeader',
method: 'get',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': 'axios/0.20.0'
},
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],
data: undefined
},
request: Writable {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object]
},
writable: true,
_events: [Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError]
},
_eventsCount: 2,
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: 10485760,
protocol: 'http:',
path: '/api/getAllDealHeader',
method: 'GET',
headers: [Object],
agent: undefined,
agents: [Object],
auth: undefined,
hostname: 'localhost',
port: '9000',
nativeProtocols: [Object],
pathname: '/api/getAllDealHeader'
},
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
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: [Socket],
connection: [Socket],
_header: 'GET /api/getAllDealHeader HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/0.20.0\r\n' +
'Host: localhost:9000\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
method: 'GET',
path: '/api/getAllDealHeader',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object: null prototype]
},
_currentUrl: 'http://localhost:9000/api/getAllDealHeader'
},
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON]
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object: null prototype]
},
_currentUrl: 'http://localhost:9000/api/getAllDealHeader'
},
response: undefined,
isAxiosError: true,
toJSON: [Function: toJSON]
}
My code is
const getData = async url => {
try {
const response = await axios.get(url);
const data = response.data;
console.log(data);
} catch (error) {
console.log(error);
}
};
cron.schedule("59 * * * * *", () => {
console.log("running a task every half minute");
let url = 'http://localhost:9000/api/getAllDealHeader'
getData(url);
})
I'm using MySQL as my DB and sequelize as my ORM.
Can someone help me, where am I going wrong and what should I do..
the variable name you are using in your function is incorrect it's lowercase but you are using uppercase in function.
cron.schedule("59 * * * * *",async () => {
console.log("running a task every half minute");
let url = 'https://jsonplaceholder.typicode.com/posts/1'
await getData(url);
})

Categories