503 error on post request from nodejs application - node.js

Im Trying to create ticket with attachment using request module of NodeJs. But not able to do so. I get an error: "Exception":"API Gateway encountered an error. Error Message: Native service provider error. Code : 503.
Following is the code used when making the post request.Is there any error in the api call?
var options = {
method: 'POST',
uri: URL,
headers: {
'Content-Type': 'application/json',
'x-Gateway-APIKey': KEY,
'Authorization': token
},
formData: {
'entry': JSON.stringify({
"values": {
"key1" : value1,
"key2" : value2
},
"options": {
"contentType": "application/json"
}
}),
'attach-z2AF_Act_Attachment_1': {
'value': fs.createReadStream(attachment),
'options': {
'contentType': 'application/octet-stream'
}
}
}
};
The post request works fine through postman.
Update on the issue:Seems the issue is with
'attach-z2AF_Act_Attachment_1': {
'value': fs.createReadStream('sample.txt'),
'options': {
'contentType': 'application/octet-stream'
}
}
Do I need convert 'sample.txt' to binary format before passing in 'value' ?

Related

Using Request to post from NodeJS

I am running into an issue with posting a json doc via request from my nodeJs app.
The problem is for me how to pass the json doc to post. Here is what works for me
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: { "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "</p>\r\n\r\n<ul type=\"disc\">\r\n\t<li><strong>Ready to Use Experiences</strong> – Get instant access to our fully configured and integrated environments allowing you to use and experience the products as a customer would in their own deployment. We’ve set up the products alongside partner solutions so you can experience the entire ecosystem including Office 365, Salesforce, and more. </li>\r\n</ul>"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#ueser.com"
}} ]}}}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
the problem i have is if i want to pass the body from a string like this
var mybody = `{ "message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "html",
"content": "This is a test"
},
"toRecipients": [
{
"emailAddress": {
"address": "test#user.com"
}
}]}}`
and then call it like this
const options = {
url: 'http://localhost/message/send/981f1507-2df2-4011-8f55-5460897fcde6',
method: 'POST',
json: true,
body: mybody
}
request(options, function(err, res, body) {
console.log(res.statusCode)
})
which throws errors like
SyntaxError: Unexpected token " in JSON at position 0
Have you tried using stringify? Node.js has a a built in module called querystring.
const querystring = require("querystring");
const myStringBody = querystring.stringify(myBody);
Then write it to your request.
req.write(myStringBody);

Provisional headers are shown

I am using Extjs in web and node.js in the api side. I called the api defined, from the web. I passed params and required data as request, but its showing the below error and request is unsuccessful.
Here is the api call code:
Ext.Ajax.request({
url: "http://localhost:3000/update-fund",
method: "POST",
dataType: 'json',
params: {
userId: userDocGlobal.id
},
headers: {
'Content-Type': 'application/json'
},
jsonData: {
fundId: PECalculator.selectedFund,
fundDate: getAiqDateFromPicker(Ext.getCmp("currentCalculationDateFundLevel")),
fundData: fund,
ownerId: userDocGlobal.companyid,
lpId: userDocGlobal.companyid,
role: userDocGlobal.role,
userId: userDocGlobal.id,
companyid: userDocGlobal.companyid
},
success: function (response) {
if (callback) {
callback(response);
}
if(userRole === "FREE"){
moduleObj.setFundNameAndCalcDateForFreeUser();
}
},
error: function () {
if (errorCallback) {
errorCallback();
}
}
})

How to capture dialogflow response?

I have a dialogflow intent and I want to write a javascript code to get json response of this intent and show it in an html file. I used webhook fulfillment for this intent and now I want to show chat history between dialogflow and user in an html file. I used this javascript code to extract and have dialogflow response:
baseUrl = "https://api.dialogflow.com/v1/",
$.ajax({
type: "POST",
url: baseUrl + "query",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({query: text, lang: "en", sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"}),
success: function(data) {
console.log("data",data);
prepareResponse(data);
},
error: function() {
respond(messageInternalError);
}
});
}
But the json it returns me is incorrect and has no fulfillment part in order to extract correct data and show response.
The returned json is :
id: "a0114c2a-afdb-415e-af08-e7a2c5b7d925"
lang: "en"
result: {…}
action: ""
metadata: Object { intentName: "Edit.Attributes", intentId: "9601923d-596b-44df-80de-92dff61869cf", webhookUsed: "true", … }
parameters: Object { VarName: […], percentage: "20%", currncy: "", … }
resolvedQuery: "Change the attribute vacancy rate to 20%"
score: 1
source: "agent"
speech: ""
__proto__: Object { … }
sessionId: "b1973977-20be-4cdc-85a5-7f4225cfdb5a"
status: Object { code: 200, errorType: "success", webhookTimedOut: false }
timestamp: "2018-01-24T12:35:46.342Z"
In my case, this was the solution:
Putting :
url: baseUrl + "query?v=20170712",
instead of :
url: baseUrl + "query",
in ajax call,solved my problem.
The dialogflow response is contained in speech and displayText propery.

Searching TrueVault always returns INVALID_SEARCH_QUERY

Dead simple search query only using required fields:
{ schema_id: 'xxxxxxxx-8b39-427a-8fb8-c764957fd9c6',
filter: { last_name: { type: 'not', value: 'Smith' } } }
POSTing to https://api.truevault.com/v1/vaults/xxxxxxxx-15e3-442e-aa6f-xxxxxxxx/search
When POSTing, the POST call options look like this:
{
data: { search_option: 'xxxx base64 encoded JSON.stringify of the above xxxxxxx' },
headers: { Authorization: 'Basic xxx base64 encoded API KEY xxx' }
}
Authorization is working. Result:
{ Error: failed [400] { "error": { "code":
"SEARCH.INVALID_SEARCH_QUERY", "message": "Invalid
search_option.", "type": "invalid_request_error" },
"result": "error", "transaction_id":
"9ad83046-1906-406c-87ab-963b904857c4" }
curl command for the same search query:
curl -d "{ search_option: 'eyJzY2hlbWFfaWQiOiJlOWVmYmE0NC04YjMwLTQyN2EtOGZiOC1jNzY0OTU3ZmMwZGUiLCJmaWx0ZXIiOnsibGFzdF9uYW1lIjp7InR5cGUiOiJ3aWxkY2FyZCIsInZhbHVlIjoiRnJhbnptZWllcioifX19' }"
-X POST
-H "Content-Type: application/json"
-H "Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=="
https://api.truevault.com/v1/vaults/xxxxxxxx-15e3-442e-aa6f-4xxxxxxxxxx/search
Same error:
{
"error": {
"code": "SEARCH.INVALID_SEARCH_QUERY",
"message": "Invalid search_option.",
"type": "invalid_request_error"
},
"result": "error",
"transaction_id": "b5a51185-264f-4765-a1b8-6ae9e491aa39"
}
Alex,
I don't think your curl command is formatted the way TrueVault expects. This may also be your problem in your http library. The curl command I'd expect is:
curl https://api.truevault.com/v1/vaults/xyz/search \
-XPOST \
-H "Content..."
-H "Auth..."
-d "search_option=eyJ...."
That is, the data payload is form-encoded (param1=value1&param2=value2) not JSON.
It looks like the docs for search were missing a sample curl, but you can see a similar curl for document create listed in the docs.
I ran into I believe the same issue in my juery ajax request. For me, it was that I was sending my request with header{'Content-Type':'application/json'}, but it needs to be form-data.
Working example:
var api_url = 'https://api.truevault.com/v1/vaults/' + vault_id + '/search';
var data = {
'schema_id' : schema_id,
'page' : 1,
'per_page' : 50,
'filter_type' : 'and',
'full_document' : false,
"sort": [
{
"SomeField":"asc"
}
],
'filter':{
'SomeField':{
'type':'eq',
'value': somevalue
}
}
};
data = btoa( JSON.stringify( data ) );
$.ajax({
type : 'POST',
url : api_url,
dataType : 'json',
processData : false,
headers : {
'Authorization':'Basic '+ btoa( auth_key+":" ),
},
mimeType : "multipart/form-data",
data : 'search_option='+ data,
error: function( response ) {
//
},
success: function( response ) {
//
}
});

Unable to create Eventbrite event using API

I am trying to create an event using V3 API. The parameters I am sending are:
var _event = {
"event" : {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
}
};
This is how I am sending the request using NodeJS:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event
}
I have also tried Content-Type: application/x-url-form-encoded and inside options, JSON.stringify(_event). I also tried to change _event object to:
var _event = {
"name": {
"html": "Test Event 01"
},
"description": {
"html": "Test Event 01"
},
"start": {
"timezone": "America/Chicago",
"utc": "2017-07-10T18:00:00Z"
},
"end": {
"timezone": "America/Chicago",
"utc": "2017-07-10T20:00:00Z"
},
"currency": "USD"
};
I have tried all the combinations but I always get the same response:
{
"status_code": 400,
"error_description": "There are errors with your arguments: event[currency] - Unknown parameter, event.start.timezone - This field is required., event.currency - This field is required., event.start.utc - This field is required., event[start][timezone] - Unknown parameter, event.end.utc - This field is required., event[end][utc] - Unknown parameter, event[description][html] - Unknown parameter, event[name][html] - Unknown parameter, event[end][timezone] - Unknown parameter, event[start][utc] - Unknown parameter, event.end.timezone - This field is required., event.name.html - This field is required.",
"error": "ARGUMENTS_ERROR"
}
Is there any sample create event request anywhere I can look into? What is the problem with above request?
I think the issue is that you're currently sending a form post (by virtue of using the form option), but then your parameters should look like { "event.currency": "USD", "event.name.html": "Test Event 01", ... }. If you want to send JSON, you need to use json: true and pass a JSON-serializable body:
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/json',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
// Instead of this:
// form: _event
// use this:
json: true, // says you're sending JSON
body: _event, // so the body should be JSON-serializable
};
If you want to stick with a form post, I think this should do it:
var _event = {
"event.name.html": "Test Event 01",
"event.description.html": "Test Event 01",
"event.start.timezone": "America/Chicago",
"event.start.utc": "2017-07-10T18:00:00Z",
"event.end.timezone": "America/Chicago",
"event.end.utc": "2017-07-10T20:00:00Z",
"event.currency": "USD",
};
var request = require('request');
var _headers = {
'Authorization': 'Bearer ' + _token,
'Content-Type': 'application/x-www-form-urlencoded',
}
// Configure the request
var options = {
url: EVENTBRITE_API_URL + "events/",
method: 'POST',
headers: _headers,
form: _event,
};

Resources