POST request not able to find url - json

I am new to nodejs as well as developing.
I am trying to get a set of data bat from a nutrition site in JSON format. If I formulate the url with my app and api keys along with criteria to paste into the browser I get a JSON data ok. When I try to send a POST request as the site asks for when the request comes back it says it cannot find the url. What it is doing is attaching ':443' to the end of the host url and like I said coming back as an error:
Error: getaddrinfo ENOTFOUND https://api.nutritionix.com/v1_1/search https://api.nutritionix.com/v1_1/search:443
What I would like to do is after the end of the url is append the 'postData'.
Here is my code:
var https = require('https');
var querystring = require('querystring');
var postData = { // Nutrionix required JSON formt
"appId":"MY_APP_KEY",
"appKey":"MY_API_KEY",
"query": "Lentils",
"fields": ["item_name", "nf_calories", "nf_serving_size_qty", "nf_serving_size_unit"],
"sort":{
"field":"score",
"order":"desc"
},
"filters":{
"item_type":"2"
}
};
console.log("This is header dta" + postData);
postBody = querystring.stringify(postData);
var post_options = {
host:"https://api.nutritionix.com/v1_1/search",
"port":"443",
method:"post",
"path":"/",
headers:{"Content-Type":"application/json",
'Content-Length': postBody.length
}
}
console.log(post_options);
var request = https.request(post_options,function(response){
return response;
});
I also am passing this data into the dev HTTP add-on in Chrome and getting back the proper response.
Any help would be appreciated.

Can you please take a look at this documentation?
It seems that you don't need to mention HTTPS

Take the port off, 443 is the default for HTTPS.

Related

Zoho Deluge - JSON POST

I am trying to use a POST command in deluge to recall a document. When I make the call I get back a no file found (I have verified the id is correct).
The format should come out like this: POST https://sign.zoho.com/api/v1/requests/[Request ID]/recall
https://www.zoho.com/sign/api/#recall-document
What am I doing incorrect?
//Get Zoho Request ID
resp = Sign_ID.toLong();
//add recall command
data = resp + "/recall";
// JSON
response = invokeUrl
[
url: "https://sign.zoho.com/api/v1/requests/"
type: POST
parameters: data.toString()
];
info "Attempting to recall waiver..." + response;
Verified Sign_ID is returning correct value
Verified correct API call
Verified error code
Other than what #ZohoCoder have mentioned.
From the documentation, it seems what you have done is almost right.
// Get Zoho Request ID
resp = Sign_ID.toLong();
// use a variable for the URL of the request
urlRequest = "https://sign.zoho.com/api/v1/requests/" + resp + "/recall";
// JSON
response = invokeUrl
[
url: urlRequest
type: POST
];
info "Attempting to recall waiver..." + response;

I can't resolve error with API POST function

I am trying to post data via an API interface.
I have checked the JSON of the data with JSON formatter and tested the API post in ReqBin and they work fine but when I execute it in App Script I get the same error, seemingly ignoring the attributes I put in the options variable.
Error is
{"code":"not_acceptable","message":"I can only talk JSON. Please set 'Accept' and 'Content-Type' to 'application/json' in your http request header."}
Note: I have tried sending just the data as the payload without json.stringify'ing it as it is formatted as JSON to start with.
In all cases it executes, but comes back 406
Is there another way to add 'Accept':"application/json" into the header??
My Code
function exportNation()
{
// Make a POST request with a JSON payload.
var data = {
"person":
{
"email":"mikenizzckelisaweiner#tv.com",
"last_name":"Bozzrovowski",
"first_name":"Edwzzard",
"tags":"Imported Data,Volunteer,Sign Request"
}
};
var options = {
"method":"POST",
"Content-Type":"application/json",
'Accept':"application/json",
'muteHttpExceptions':true,
'payload':JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://xyz.xyz.com/api/v1/people?
access_token=5604da84fXXXXXXXXXXXXXXXX42da1ea',options );
}
Any help would be greatly appreciated!
Additional HTTP headers need to be sent as a headers object.
See: https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#advanced-parameters
var options = {
"method":"POST",
"contentType":"application/json",
"headers": {'Accept':"application/json"},

Invalid Argument on basic API call using UrlFetchApp.fetch(url)

I'm new to Google Apps Scripts and I've been trying to make a simple Get call to a URL. I make this call from my browser: https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740 and get the respons I'm looking for. I now try to make the call from Google Apps Scripts using the following code:
function myFunction() {
var url = 'https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}'
I get a respons stating '
Message details
Invalid argument: https://accounting.sageone.co.za/api/1.1.1/Supplier/Get?apikey={4CFEEFE1-CE04-425F-82C3-DCB179C817D5}&companyid=164740 (line 4, file "Code")'
I've tried a whole bunch of permutations with no luck...
When using UrlFetchApp, you need to enter your URL parameters as part of a request parameters rather than in the URL itself. For a GET request these go directy as part of the parameters, for a POST request the parameters would be part of a payload object. Reference Documentation
Here is a modified function:
function myFunction() {
var url = 'https://accounting.sageone.co.za/api/1.1.1/Supplier/Get'
var params = {
"method": 'GET',
"apikey": "{4CFEEFE1-CE04-425F-82C3-DCB179C817D5}",
"companyid": "164740"
}
var response = UrlFetchApp.fetch(url, params);
Logger.log(response)
}
Note: This corrects your method, however, the server still requires further authentication. If you run into issues with that, ask another questions specific to that issue as well.

Im getting unexpectected token : for a valid JSON

I am working with ArcGIS, Esri request and I am trying to get a data from a webserver, but everytime I got the same "unexpected token : " error even when my response is correct.
Thanks in advance.
Here's my code:
require(["dojo/dom", "dojo/on", "dojo/dom-class", "dojo/_base/json", "esri/urlUtils", "esri/config", "esri/request", "dojo/domReady!"], function(dom, on, domClass, dojoJson, urlUtils, esriConfig, esriRequest) {
// fallback to proxy for non-CORS capable browsers
// esri.config.defaults.io.proxyUrl = "/arcgisserver/apis/javascript/proxy/proxy.ashx";
esriConfig.defaults.io.proxyUrl = "/proxy/proxy.ashx";
dom.byId("url").value = "http://api.citybik.es/v2/networks/dublinbikes";
dom.byId("content").value = "";
//handle the Go button's click event
on(dom.byId("submitRequest"), "click", getContent);
function getContent(){
var contentDiv = dom.byId("content");
contentDiv.value = "";
domClass.remove(contentDiv, "failure");
dom.byId("status").innerHTML = "Downloading...";
// //get the url
// var url = urlUtils.urlToObject(dom.byId("url").value);
// console.log("EL URL path",url.path)
// console.log("EL URL query",url.query)
// var requestHandle = esriRequest({
// "url": url.path,
// "content": url.query
// });
// requestHandle.then(requestSucceeded, requestFailed);
function requestSucceeded(data) {
console.log(data);
}
function requestFailed(error) {
console.log("Error: ", error.message);
}
var request = esriRequest({
url: "http://api.citybik.es/v2/networks/dublinbikes",
content: {
format: "json"
},
handleAs: "json",
callbackParamName: "retrive"
});
request.then(requestSucceeded, requestFailed);
}
}
);
Im getting:
Uncaught SyntaxError: Unexpected token : dublinbikes:2
The root problem is that you're getting esri.request a bit confused with what you're asking for, and what the server is giving back. Because you're making a request on a different domain (api.citybik.es) from where you're running the code (whatever your host is), you need to use either:
CORS
JSONP
a proxy
to get around the browser's security restrictions. There's plenty of detail on SO about these, I won't dribble on further.
Your code has two methods configured - the callbackParamName tells esri.request to use JSONP, and you've also got a proxy set just in case. The callbackParamName tells it to only use JSONP though, so the proxy is ignored.
Now the real problem, as I noted in a comment above, is that v2 of the CityBikes API doesn't actually seem to support JSONP, so your callback parameter is ignored and the server gives you back straight JSON. esri.request is expecting JSONP, and voila - unexpected token :. Requesting
http://api.citybik.es/v2/networks/dublinbikes?callback=stackoverflow
returns:
{
network: {
company: "JCDecaux",
href: "/v2/networks/dublinbikes",
....
See? No mention of our stackoverflow variable. If you look at v1 of the API instead, that DOES support JSONP. Requesting
http://api.citybik.es/dublinbikes.json?callback=stackoverflow
returns:
stackoverflow(
[
{
bikes: 1,
name: "Fenian Street",
idx: 0,
....
...and there is our stackoverflow variable. OR you can remove the callbackParamName from your esriRequest, and see if your proxy will process the JSON from the v2 address.

Chrome API responseHeaders

Based on this documentation: https://developer.chrome.com/extensions/webRequest.html#event-onHeadersReceived
I tried to display the response via the console like:
console.log(info.responseHeaders);
But its returning undefined.
But this works though:
console.log("Type: " + info.type);
Please help, I really need to get the responseHeaders data.
You have to request the response headers like this:
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log(details.responseHeaders);
},
{urls: ["http://*/*"]},["responseHeaders"]);
An example of use. This is one instance of how I use the webRequest api in my extension. (Only showing partial incomplete code)
I need to indirectly access some server data and I do that by making use of a 302 redirect page. I send a Head request to the desired url like this:
$.ajax({
url: url,
type: "HEAD"
success: function(data,status,jqXHR){
//If this was not a HEAD request, `data` would contain the response
//But in my case all I need are the headers so `data` is empty
comparePosts(jqXHR.getResponseHeader('redirUrl')); //where I handle the data
}
});
And then I silently kill the redirect while scraping the location header for my own uses using the webRequest api:
chrome.webRequest.onHeadersReceived.addListener(function(details){
if(details.method == "HEAD"){
var redirUrl;
details.responseHeaders.forEach(function(v,i,a){
if(v.name == "Location"){
redirUrl = v.value;
details.responseHeaders.splice(i,1);
}
});
details.responseHeaders.push({name:"redirUrl",value:redirUrl});
return {responseHeaders:details.responseHeaders}; //I kill the redirect
}
},
{urls: ["http://*/*"]},["responseHeaders","blocking"]);
I actually handle the data inside the onHeadersReceived listener, but this way shows where the response data would be.