I am using auto generated the ajax with Postman 3, so you can tell if it's the correct way to do it, but this isn't my main question. Now, when I type the "data" field like this, it works
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "8de908df-f970-524c-eb8b-d2f7f621a3ac"
},
"processData": false,
"data": "{\"name\":\"Peter\",\"id\":11}"
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Now my question is, how do I put custom parameters in the "data" field.
I want something like this
var arr = [{"name": "Peter", "id": 12}, {"name": "Demeter", "id": 15}];
var settings = {
"async": true,
"crossDomain": true,
"url": "https://baas.kinvey.com/appdata/kid_B1BHxEN7/people/",
"method": "POST",
"headers": {
"authorization": "Basic Z2VzaGE6MTIzNA==",
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "e37d3063-406d-02c3-803f-0f32666b9d70"
},
"processData": false,
data: {"name": arr[0].name, "id": arr[0].id}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When i send this POST request it gives me back 400(Bad request)
jQuery does not format your request as JSON but only as data url. You have to do this yourself:
data: JSON.stringify({"name": arr[0].name, "id": arr[0].id})
You need to convert the string to JSON format using stringify. Here is link to explanation:
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Related
I am trying to use the Citi Bank Open API in my React Native mobile app. I was able to call the API to let user sign in with their Citi Bank account and get the client authorization code. However, when I was trying to call another API for validating the code I got, it returned a weird error without any description.
I suspect problems may be caused by:
my app is still in development stage
I didn't do the calling on the redirect uri, but the domain is definitely the same
The API is supposed to return an access token for further interaction, but all I got is the error. I wanna know what might be the possible mistakes.
This is my first time trying to use an open API inside my app. Any suggestion will be much appreciated.
Official docs from Citi (may need to register an account):
https://sandbox.developerhub.citi.com/api/hong-kong/retail-bank/identity-security/authorize/documentation
Calling the API:
fetch(
"https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/hk/gcb",
{
method: "POST",
body: new URLSearchParams({
grant_type: "authorization_code",
code: auth_code,//got from the response of GET /authCode/oauth2/authorize
redirect_uri: "http://localhost:19000/redirect",
}),
headers: new Headers({
"Cross-Domain": true,
Accept: "application/json",
Authorization:
"Basic " + btoa(CITI_CLIENT_ID + ":" + CITI_CLIENT_SEC),
"Content-Type": "application/x-www-form-urlencoded",
}),
}
)
.then((data) => {
console.log(data);
data.json();
})
.then((result) => {
console.log(result);//undefined
});
Response:
Response {
"_bodyBlob": Blob {
"_data": Object {
"__collector": null,
"blobId": "f09ce99b-1a3b-4251-9a73-5a4a809a6296",
"offset": 0,
"size": 88,
},
},
"_bodyInit": Blob {
"_data": Object {
"__collector": null,
"blobId": "f09ce99b-1a3b-4251-9a73-5a4a809a6296",
"offset": 0,
"size": 88,
},
},
"bodyUsed": false,
"headers": Headers {
"map": Object {
"access-control-allow-credentials": "true",
"access-control-allow-headers": "",
"access-control-allow-methods": "",
"access-control-allow-origin": "",
"access-control-expose-headers": "",
"connection": "close",
"content-length": "88",
"content-type": "application/json",
"date": "Thu, 24 Mar 2022 06:37:39 GMT",
"set-cookie": "CITI_SITE=gtdc; expires=Thu, 24-Mar-2022 06:57:39 GMT; path=/; domain=sandbox.apihub.citi.com; secure; HttpOnly",
"x-akamai-citisite": "GTDC",
"x-backside-transport": "FAIL FAIL,FAIL FAIL",
"x-global-transaction-id": "6e68aa42623c11b387504e5d",
},
},
"ok": false,
"status": 400,
"statusText": "",
"type": "default",
"url": "https://sandbox.apihub.citi.com/gcb/api/authCode/oauth2/token/hk/gcb",
}
I'm trying to get this code to track user visit but I can't manage to get it to work.
When I do this in Postman, I get successful, but to put it in the HTML I get nothing.
How do I make the script activate when user visit website? I need to pass on the values to a /registerLead on form submission afterwards.
<script>
var settings = {
"url": "https://api31.trackinglink3.com/SignalsServer/api/trackVisit",
"method": "GET",
"timeout": 0,
"headers": {
"apikey": "apikey",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"devicetype": "",
"Offer": "",
}
};
</script>
Just use ajax function for this. check snippet below..
$(function(){
$.ajax({
method: "GET",
url: "https://api31.trackinglink3.com/SignalsServer/api/trackVisit",
"timeout": 0,
"headers": {
"apikey": "apikey",
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"devicetype": "",
"Offer": "",
}
})
.done(function() {
// your done code here
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm working on implementing some Spotify calls into a project using the Spotify API and the first thing I have to do is authenticate. I tested out the Spotify API endpoint by using Restlet (a REST API client) and my call is successful with the response of:
{ "access_token":
"BQC2PbOsWsnkfzcMUMW5YeJh9VGgE7uSQ-ubpO5kekyn3IIq0yVqoIW6Rx-5sQLJyH8R8wik6PzcFfzFDCU",
"token_type": "Bearer", "expires_in": 3600, "scope": "" }
I then implemented the POST call in my React app using javascript and it worked!
async function getSpAccessToken(component) {
const [initSpotResponse] = await Promise.all([
axios.post("https://accounts.spotify.com/api/token",
querystring.stringify({
grant_type: 'client_credentials'
}),
{
headers: {
'Authorization': `Basic ${encodedString}`,
'Content-type': 'application/x-www-form-urlencoded'
}
}
).catch((error) => {
console.log("getSpAccessToken ERROR = " + JSON.stringify(error))
})
]);
const spAccessToken = await initSpotResponse.data.access_token
}
But eventually when the token expires, my calls to Spotify respond with a "access_token expired" message, as expected. I go back and re-authenticate using the same getSpAccessToken() function but I get this as a response:
{
"data": "",
"status": 200,
"statusText": "OK",
"headers": {},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OTaA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
},
"method": "post",
"url": "https://accounts.spotify.com/api/token",
"data": "grant_type=client_credentials"
},
"request": {}
}
The response is confusing because a) the status code is OK and b) because the data field is empty (this is where the access token resides). I then try to use my REST client, Restlet, to try the same call again and I get an access_token in my response! Then I go back and refresh my page and my getSpAccessToken() function gets called and this time it returns a data object:
{
"data": {
"access_token": "BQCuvTWeJlixkOsuAhKPClKWaXTaSPiuycNY6Z2EKKQLqsDyGyXdDcn4RR4tVq6--1HHJ_l1ViDlCi_mN_bk",
"token_type": "Bearer",
"expires_in": 3600,
"scope": ""
},
"status": 200,
"statusText": "OK",
"headers": {
"content-type": "application/json"
},
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic ZmY1NmFiZTc3OTJmNDI2ZWE0MWE3NzFkNzA3ZDY2OaTA6YjJjY2EyZGVkZDM5NDliMGE2YzVlMTU4MjQ0NmM5YzU="
},
"method": "post",
"url": "https://accounts.spotify.com/api/token",
"data": "grant_type=client_credentials"
},
"request": {}
}
My question: Why is it that when I need to refresh my token, my javascript getSpAccessToken() call returns a response with an empty data field until after I use my REST client to make that same call?
Im trying to access to parameter value from response.
$.ajax({
type: "POST",
url: "",
dataType: 'text',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "action" : "create", "resource" : {"name" : "teddssssssssddsssdsddddsdddwdsdssdsddi", "description": "Test Tenant Description","parent": {"href": "localhost"}}}',
success: function(as) {
alert(as[0][0]["id"]);
}
});
in the success area i got the response, in json. I want to access to the id value, but i cant. always says undefined, i tried different options.
this is the response format.
{
"results": [
{
"href": "localhost/1111111",
"id": "100000000111",
"name": "test",
"ancestry": "1000011111",
"divisible": true,
"description": "Test Tenant Description",
"use_config_for_attributes": false,
"default_miq_group_id": "10021200000173"
}
]
}
I dont know if i can access direct to the parameter or better get the response as text and split.
The response has a different structure.
Your response is an object with one property and value is an array of objects.
something like {'results': [...{}]}
Key 0 does not exist.
const data = {"results":[{"href":"localhost/1111111","id":"100000000111","name":"test","ancestry":"1000011111","divisible":true,"description":"Test Tenant Description","use_config_for_attributes":false,"default_miq_group_id":"10021200000173"}]};
console.log(data.results[0].id);
I am working with Pluralsight API and their API responds CSV files as results, which I would like to grab this data from response and print out.
this is the URL of the Pluralsight API:
https://app.pluralsight.com/plans/api/reports/docs
and this is the code I am trying to do:
request
.get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
.on('response', function (response) {
res.json(response);
})
The response does not show any data except for the data as below:
{
"statusCode": 200,
"headers": {
"cache-control": "private",
"content-disposition": "attachment; filename=Users.csv",
"content-type": "text/csv",
"date": "Fri, 27 May 2016 03:42:06 GMT",
"ps-build": "2016.5.1849.0",
"ps-node": "0Q5JR",
"ps-responsetime": "00:00:00.1406230",
"content-length": "11391",
"connection": "Close"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": "api.pluralsight.com",
"port": 443,
"hostname": "api.pluralsight.com",
"hash": null,
"search": "?planId=x&token=y",
"query": "planId=x&token=y",
"pathname": "/api-v0.9/users",
"path": "/api-v0.9/users?planId=x&token=y",
"href": "https://api.pluralsight.com/api-v0.9/users?planId=x&token=y",
},
"method": "GET",
"headers": {}
}
}
Is there anyway that I get get the file from attachment and extract it?
Thanks
Request body is accessible through data and end events.
var body = [];
request
.get('https://api.pluralsight.com/api-v0.9/users?planId=x&token=y')
.on('data', function (chunk) {
body.push(chunk);
})
.on('end', function () {
body = body.join('');
// body now contains csv contents as a string
});