No response Data Angularjs POST / TypeScript - angularjs

I'm trying to test AngularJS's post method out, but so far I have not figured out how to get it work.
Here is my code snippet.
parameter = { categoryName: '' }; <- just a dummy parameter purposely set to '' for testing purposes
this.httpService({
method: 'POST',
url: '/svc_templates/svc_fetch_category.php',<- Just echoing some JSON string.
data: parameter
}).then(function (response) {
console.log(response);
The response I'm getting is shown below.
It seems that a call to the php file is going through, but the actual data(JSON) is not returning for some reason...
Could anyone help me out?

Make sure that the server .php file is actually working using curl e.g.:
curl -X POST -d #filename.txt http://example.com/svc_templates/svc_fetch_category.php --header "Content-Type:application/json"
Where filename.txt contains the JSON data you want to send.

Related

BOX API by Google Apps Script - new file version upload

I've already asked the GAS community but I was advised to continue asking here...
So far I'm able to connect to BOX and get a list of files and I can download a file from BOX as well.
The whole idea is to download a file using BOX API, edit it and upload it back as a new file version using the BOX API.
I'm unable to make the last part working as it gives me error code 400.
Here is the function.
function uploadNewFileVersion() {
//767694355309 testing
var boxFileId="767694355309";
var newVerFile = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
var confirmAuthorization = getBoxService_().getAccessToken();
//var parent = { "id": "0" };
//"name": "apiNewVersion.xlsx",
//"parent": parent,
var payload = {
"file": newVerFile
}
var headers = {
'Authorization': 'Bearer ' + confirmAuthorization
}
var options = {
"method": "post",
"muteHttpExceptions": true,
"contentType": "multipart/form-data",
"headers": headers,
"payload": payload
}
var apiHtml = "https://upload.box.com/api/2.0/files/"+boxFileId+"/content/";
var response = UrlFetchApp.fetch(apiHtml, options);
Logger.log(response.getResponseCode());
var a = 1;
}
The boxFileId is the file on the box.
The newVerFile is the one downloaded from Box and updated. I need to make it as a new version of the Box file.
Could you please advise?
Thank you!
PEtr
I think parent and name is optional so I commented it out.
If I don't getBlob, then it returns 415 istead.
I believe your goal and situation as follows.
You want to upload a file of Google Drive using Box API with Google Apps Script.
From your question, I cannot find the official document of the method of API that you want to use. But, from the endpoint https://upload.box.com/api/2.0/files/"+boxFileId+"/content/ in your script, I guessed that you wanted to use "Upload file version".
Values of your access token and file ID are valid for using the API.
If my understanding of your question is correct, how about the following modification?
Modification points:
When I saw the official document of "Upload file version", I confirmed the following sample curl. In this case, it is considered that when the following curl command is converted to Google Apps Script, the request might work.
$ curl -i -X POST "https://upload.box.com/api/2.0/files/12345/content" \
-H "Authorization: Bearer <ACCESS_TOKEN>" \
-H "Content-Type: multipart/form-data" \
-F attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" \
-F file=#<FILE_NAME>
From the curl command, it is found that attributes and file are sent as form and files.
And, I thought that attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" might should be attributes="{\"name\":\"Contract.pdf\", \"parent\":{\"id\":\"11446498\"}}".
When I saw your current script, it seems that multipart/form-data is used for contentType. In this case, boundary in the request body is required to be included. Fortunately, at UrlFetchApp, in the case of multipart/form-data, when contentType is not used, the content type is automatically included in the request header. I think that in your case, this can be used.
In your script, attributes="{"name":"Contract.pdf", "parent":{"id":"11446498"}}" is not included. But I thought that you might use it in the future script. So in this answer, this is also included.
When above points are reflected and the sample curl command on the official document is converted to Google Apps Script, the script becomes as follows.
Sample script:
Please copy and paste the following script to the script editor and set the variables, and run the function of myFunction. By this, the request same with the sample curl is requested with Google Apps Script.
function myFunction() {
const accessToken = "###"; // Please set your access token.
const fileId = "###"; // Please set your fileId.
const fileBlob = DriveApp.getFileById("1sK-jcaJoD0WaAcixKtlHA85pf6t8M61v").getBlob();
const metadata = {name: "Contract.pdf", parent: {id: "11446498"}}; // Please set your file metadata.
const params = {
method: "post",
headers: {Authorization: `Bearer ${accessToken}`},
payload: {
attributes: JSON.stringify(metadata),
file: fileBlob,
},
muteHttpExceptions: true,
};
const url = `https://upload.box.com/api/2.0/files/${fileId}/content`;
const res = UrlFetchApp.fetch(url, params);
console.log(res.getContentText());
}
I could confirm that above sample script is the same request with above sample curl.
If you don't want to use the file metadata, please remove the line of attributes: JSON.stringify(metadata), from payload.
Note:
In this case, the maximum data size ("URL Fetch POST size") of UrlFetchApp is 50 MB. Please be careful this. Ref
About the limitation of file upload of Box API, please check https://developer.box.com/guides/uploads/.
If your access token and file ID are invalid, I think that an error occurs. So please be careful this.
References:
Upload file version
Class UrlFetchApp

Best method to send a complex json request with Convertigo

I have a complex json request that I'd like to POST to an api but I can't find the proper way to do this inside Convertigo Studio. Could anyone please indicate me the best way to do this?
Here is the request I'm send through curl that gives me the results. These result will be used by the front to display data.
curl -k -H "Accept: application/json" --compressed -XPOST https://myserverurl/api/search -d #- << EOF
{
"api-key":"somekey",
"usage":"someusage",
"criteria":{
"timestamp":{"from-to":{"date-pattern":"yyyy/MM/dd-HHmmss","from":"2019/07/28-000000","to":"2019/08/27-235959"}},
"timestamp-field":"timestamp",
"metric":"*",
"filter":{
"and":
[
{"eq":{"attribute":"type","value":"sometype"}},
{"simple-query":{"query":"_exists_:city"}},
{"neq":{"attribute":"status","value":"1"}}
]
}
},
"info":"someinfo",
"size":10000,
"mode":"last-hits",
"format":{"tabular":{"columns":["col1", "col2","col3"],
"last-hits-columns":["name"],"order-by":[{"name":"name","direction":"ASC"}]},
"timestamp":{"date-pattern":"dd/MM/yyyy HH:mm:ss"}},
"index":"someindex",
"last-hits-count":"1"
}
EOF
I now would like to transpose that into a Convertigo approach using the proper connector and transactions but so far I'm hitting a wall. Any help is appreciated.
update: So I've managed to contact the API, i.e. reproducing the first part of the curl, by implementing a HTTP_Connector and then a HTTP_Transaction. The server is answering in the expected way.
Now what I can't do is posting the json string. I've tried implementing a http_single_variable which default value is that json string but it doesn't work, I get the following error:
HTTP result {ContentType: application/json, Length: 277}
{"error":{"request":"http://localhost:8550/api/search","message":"Unexpected character ('H' (code 72)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: java.io.InputStreamReader#6c195833; line: 1, column: 2]","target":"/search"}}
The error seems to be coming from the header, which has been defined as Accept, application/json. When I remove it I get a HTTP 500 Error from the server.
To post a JSON body in a Convertigo request you have to add a variable "__body" to your transaction:
HTTP single-valued variable
If your API returns a JSON response, you should use a JSON_HTTP_transaction instead of your HTTP_Transaction transaction.
Set "HTTP verb" property transaction to POST and "HTTP headers" property to "Content-type, application/json".
The value of the __body variable is set in a sequence by a Sequence_JS step like this:
var data = {
"param1": "value1",
"param2": "value2",
...
};
Then, use a jElement step to transform "data" to a JSON string source:
JSON.stringify(data)
in "Expression" property.
Next step is the Call of your transaction. In the __body Source point to the jElement text.
Here is a link to a Convertigo (7.5.7+) sample:
useBody.car
Hope that Helps.

How to call GET api to send data in BODY using axios?

I'm trying to send data in a body using the GET method.
It's working fine when i try to run using POSTMAN/cURL/Python but it's not working using AXIOS(ReactJS).
cURL:
curl -X GET \
http://127.0.0.1:8000/xyz/xyz/ayx-api/ \
-H 'Authorization: Token 980e4e673a9cfb4c99cb35313f65a446aa44faf7' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 1ee27393-b4b0-446a-b613-bd319e02e3c8' \
-H 'cache-control: no-cache' \
-d '{"dataId": 1, "date": "2018-03-01", "days": 9 }'
this curl working fine
Using Axios:
import axios from 'axios';
const baseUrl = process.env.BACKEND_SERVER_URL;
export const fetchDataObjects = async() => {
const header = {
'Content-Type': 'application/json',
'Authorization': `Token ${localStorage.token}`,
}
const data ={"dataId": 1, "date": "2018-03-01", "days": 9 }
const res= await axios.get(`${baseUrl}/ayx-api/`,{data:JSON.stringify(data)}, {headers: header})
// above line need to helop
return res.data;
}
How can i send data in body using axios in get method?
Thanks in advance.
The HTTP GET method requests shouldn't have a request body, and axios can't create a GET request with a body. It also can't create a query string for you, if you want to pass a query string, you have to do it manually, or with something like qs:
axios.get(`${baseUrl}/ayx-api/${qs.stringify(data)}`)
UPD: turns out that even manually you can't add a body to a GET request using the fetch method in the console of your browser (I've tried to do it in Google Chrome 108 and Firefox 107 they both return similar errors Request with GET/HEAD method cannot have body.). I guess it'll take some time for browsers to support it. As a workaround you can try switching to POST method on both backend (with a different path to make no collisions) and frontend.
Original answer:
You can create a GET request with body. You need to pass the body to AxiosRequestConfig (the second parameter of the axios.get method).
let body = {hit: "floor"} //can be a string or an object (refer to the docs)
axios.get(`url`, {data: body})
AxiosRequestConfig also accepts headers if you need any.
axios.get(`url`, {headers: {"Key": "keykeykey"}, data: body})
Thought the documentation says that the data is
Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
you can actually pass the body (tested in axios 0.27) and the server should¹ receive it. And you also need to make sure that the server will accept such request since the constrain in the specification was removed almost a decade ago.
¹ - Citation from MDN's GET page:
Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined. It is better to just avoid sending payloads in GET requests.
I'm using axios for NestJS e2e testing and NestJS 9.1 with ExpressJS will accept body in the GET request (yes, you can retrieve it with the #Body() decorator).

How to create a Perl API to pass data back to an angularjs $http request?

I'm using angular 1.5.7 and perl 5.16.2. I don't have the ability to use any external libraries or switch tools - I'm stuck just using what's included with these two.
The angular controller is making calls to a perl file. I'm able to make POST requests successfully, and my GET requests are returning status 200 but aren't showing the data that I am expecting to see. Right now I'm just working with a simple example to try and narrow down where things are going wrong, and I think I just don't know the format to return values from the perl file.
My controller GET method looks like so:
$http({
method : "GET",
url : "filename.pl",
params:{}
}).then(function successCallback(response) {
console.log(response.records);
}, function errorCallback(response) {
console.log(response);
});
and the perl code being called in filename.pl is:
my $string = q{{"records":{"2":{"City":"México D.F.","Country":"Mexico","Name":"Ana Trujillo Emparedados y helados"},"1":{"Name":"Alfreds Futterkiste","Country":"Germany","City":"Berlin"}}}};
return $string;
The string is just a dummy variable to see if passing things back works - it won't be the final data. I have verified it is valid JSON as well. Here's what the response from the server looks like:
{"data":"","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"glwizardutils.esp","params":{"FUNCTION":"initcheckboxes","CONTEXTID":"432"},"headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
The data field is totally blank, and the response field doesn't work at all. I can verify it's hitting the perl file - like I said, POST requests work fine and I included some printouts that verify it's in the correct method, but it's just not returning anything. What should I be doing here instead to get this to work?
If filename.pl is invoked with HTTP, then it should be writing an HTTP response to standard output. At a minimum:
print "HTTP/1.1 200 OK\n";
print "Content-type: application/json\n";
print "\n";
my $string = q{{"records":{"2":{"City":"México ..."}}}};
print $string;
Several frameworks and modules exist in Perl and virtually every other language to handle the repetitive aspects of writing a proper response, which you will want to look into as your Perl server-side script gets more demanding.

Parse.com RESTAPI&angularJS query constraints key issue

I have a function which does a HTTP GET request on Parse, using the code below. (I'm using AngularJs).
$http({ method: 'GET',
url: 'https://api.parse.com/1/classes/foo',
headers:{
"X-Parse-Application-Id": "MYPARSEAPPID",
"X-Parse-REST-API-Key": "MYPARSERESTAPIKEY",
"X-Parse-Session-Token": UserService.sessionToken,
},
params: {
where:{"toto":{"$gt":42}}
}
}).success(function(data, status) {
/* DO SOMETHING*/
}).error(function(data, status) {
/* DO SOMETHING */
});
I wrote this code using Parse' REST documentation (https://www.parse.com/docs/rest#queries-constraints)
which give this example (curl):
curl -X GET \
-H "X-Parse-Application-Id:..............." \
-H "X-Parse-REST-API-Key:.............." \
-G \
--data-urlencode 'where={"score":{"$gte":1000,"$lte":3000}}' \
https://api.parse.com/1/classes/GameScore
This is the result of the AngularJS request above seen through Chrome's Dev Tools:
where:{"toto":{}}
And this this the result of the same code, without the '$' character (it doesn't work, but the requet is sent as it should):
where:{"toto":{"gt":42}}
As you can see, the constraint disappears because of the '$' character.
I supposed angular doesn't let us use '$' as it is used for Angular properties/methods.
Any suggestion/ideas/example will be very helpful.
Edited:
I tried to stringify the params as RobH said, click here to look at the result seen through Chrome's Dev Tools.
The result of this query seems ignore completly the given contraints, even if the '$' caracter hasn't been striped. I found that someone else tried to stringify the params (How to pass parameters to $http in angularjs?), but according to the last comment, it "does not work ({method:'GET', url:'/search', stringifiedJsonData} is not a valid JavaScript literal)". I'm not sure about the relevance of this comment as I'm new at AngularJs and web in general.
Any other ideas ?

Resources