es6 fetch request for salesforce desk api - javascript

I am trying to set up public forms on a wp site so people can schedule an exam without a login, which is supposed to link to the clients salesforce desk app. the Desk API docs recommend this.
$ curl https://yoursite.desk.com/api/v2/cases \
-u email:password \
-X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{"subject":"Test"}'
I admittedly have relied on es6 syntax for my inexperience with rest api calls and am having trouble validating my POST request. My javascript looks like so, but I get a 404 as well as a "Response to preflight check doesn't pass access control check." I'm assuming I am missing some credentials.
document.querySelector('#submitDesk').addEventListener('click', schedule);
function schedule() {
var firstname = document.querySelector('#firstname').value;
var lastname = document.querySelector('#lastname').value;
var email = document.querySelector('#email').value;
fetch('https://foo.desk.com/api/v2/cases', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept' : 'application/json'
},
body: {
'firstname': firstname,
'lastname': lastname,
'email': email
}
})
.then(function(response) {
return response.json();
})
.then(function(response) {
console.log(response);
})
}

Related

how to translate curl into javascript POST request

I am trying to connect to payment api named PayU, they provide example on how to connect via curl one is to connect via rest api
curl -X POST https://secure.payu.com/pl/standard/user/oauth/authorize \
-d 'grant_type=client_credentials&client_id=145227&client_secret=12f071174cb7eb79d4aac5bc2f07563f'
and one is to connect via SDK which I would also like to use, but this one needs additional settings in the shop, and I'm having trouble with the first one so if someone would be kind enough to decipher the other one as well would be great
curl -X POST https://secure.payu.com/pl/standard/user/oauth/authorize \
-H "Cache-Control: no-cache"
-H "Content-Type: application/x-www-form-urlencoded"
-d 'grant_type=trusted_merchant&client_id=[provided by PayU]&client_secret=[provided by PayU]&email=[users email]&ext_customer_id=[Id of the customer used in merchant system]'
In curl the first one delivered the token without problems, however I am trying to do this same in code, and I am unable to. This is my code:
fetch('https://secure.payu.com/pl/standard/user/oauth/authorize', {
method: 'POST',
body: JSON.stringify({
'grant_type': 'client_credentials',
'client_id': '145227',
'client_secret': '12f071174cb7eb79d4aac5bc2f07563f',
})
}).then(res => {
if (!res.ok) {
throw new Error("Fetching payU failed, please try again later!");
}
return res;
})
.then(data => {
console.log(data)
return { payUdata: data }
})
.catch(err => {
console.log(err);
});
A basic Post body isn't a serialized json, data looks like query params, just like in the curl
{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: "grant_type=client_credentials&client_id=145227&client_secret=12f071174cb7eb79d4aac5bc2f07563f")
}
from #BankBuilder comment:
function querifyObject(obj){
return new URLSearchParams(Object.entries(obj)).toString();
}
and then:
{
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
body: querifyObject({
'grant_type': 'client_credentials',
'client_id': '145227',
'client_secret': '12f071174cb7eb79d4aac5bc2f07563f',
})
}

Axios library failing to respond for post request, trying with curl and postman works

Below is the following code I am using to access a remote server:
axios({
method: 'post',
url: 'SERVER URI',
data: {"key1": "val1","key2": "val2"},
headers: {
'Authorization': 'Bearer ${token}',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((res) => {
console.log('Response **', res);
resolve(res.data);
}).catch(err => {
console.log('Error from server is ***', err.response);
reject(err.response.data);
});
here token is an oauth2 bearer token using client credentials as grant-type. I am getting a 404 response for this with data: {message: ''}. But I tried the same in postman as well as with a curl request. For both these instances, I got back a valid 200 response.
I am attaching the curl request also,
curl --location --request POST 'URI' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer TOKEN' \
--header 'Content-Type: application/json' \
--data-raw '{"key1": "val1","key2": "val2"}'
I may be overlooking something but I am going crazy as to not understanding what I am missing. Any help for this is appreciated
You can try to use formData like that:
const data = new FormData()
data.append('key1', 'val1')
data.append('key2', 'val2')
axios({
method: 'post',
url: 'SERVER URI',
data: data,
headers: {
'Authorization': 'Bearer ${token}',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then((res) => {
console.log('Response **', res);
resolve(res.data);
}).catch(err => {
console.log('Error from server is ***', err.response);
reject(err.response.data);
});
A 404 response makes me think that maybe the url has a typo in it, but I have seen APIs that respond with 404 as a security measure when authorization fails so it could be a bad Authorization header, too.
There's a typo in the code sample from the original question:
headers: {
'Authorization': 'Bearer ${token}',
...
}
the single quotes surrounding the Bearer ${token} would need to be changed to backticks in order for the template string to actually be expanded.
As it is now, the Authorization header is actually being sent with the literal string ${token} as your token.

How to do this registration okta curl request in javascript

I am trying to register a new user in OKTA in Javascript with a curl mentioned here
.
I want to make a curl format like this
curl -v -X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: SSWS ${api_token}" \
-d '{
"profile": {
"firstName": "Isaac",
"lastName": "Brock",
"email": "isaac.brock#example.com",
"login": "isaac.brock#example.com",
"mobilePhone": "555-415-1337"
},
"credentials": {
"password" : { "value": "tlpWENT2m" }
}
}' "https://dev-662976.oktapreview.com/api/v1/users?activate=false"
This is part of code I write
handleSubmit(e){
e.preventDefault();
var data = {};
var profile = {};
var credentials = {};
profile['firstName'] = document.getElementById('firstName').value;
profile['lastName'] = document.getElementById('lastName').value;
profile['email'] = document.getElementById('email').value;
profile["login"] = document.getElementById('email').value;
profile['mobliePhone'] = "555-415-1337";
data['profile'] = profile;
credentials['password'] = {"value":document.getElementById('password').value};
data["credentials"] = credentials;
this.registrationApiCall(data);
//console.log(data);
//registrationApiCall(data);
}
registrationApiCall(data){
return axios({
method: 'post',
url: 'https://dev-662976.oktapreview.com/api/v1/users?activate=false',
data: data,
config: {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
"Authorization": "SSWS <my_ssws_token>"
}
}
}).then(function(value) {
console.log(value);
}).catch(function(err) {
console.log(err);
});
}
I get a 403 error like this:
POST https://dev-662976.oktapreview.com/api/v1/users?activate=false 403 (Forbidden)
Register.js:72 Error: Request failed with status code 403
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
From the console of chrome, I can see two requests. They have same request url but the first is 200 and doesn't include any payload and the second include my data which is a 403 error.
I write this code referring this dude but I think his format is not correct, but it works well on his demo. Could you tell me how to make it correct?
I have no idea if I should use axios, if there is some better idea. Please tell me.

Translate curl to http request in android app

I am developing an android app with ionic 2 and I need to send data to a redcap server (https://www.project-redcap.org/, example code to interact with redcap using the provided api http://redcap-tools.github.io/projects/)
I tried to translate from curl commands to http post requests to use in the app and have so far been unsuccesful. For example, I translated the following curl that executes correctly
DATA="token=MY_TOKEN&content=project&format=csv&returnFormat=json"
CURL=`which curl`
$CURL -H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json" \
-X POST \
-d $DATA \
MY_URL
into
this.packet = { token: MY_TOKEN,
content: 'project',
format: 'json',
returnFormat: 'json',
type: 'flat',
data: 'null',
};
this.headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'});
this.http.post(this.apiurl, JSON.stringify(this.packet {headers:this.headers}).subscribe(data => {
console.log('success')
console.log(data);
}, error => {
console.log(error);
console.log("Oooops!");
});
that returns on the error branch.
Trying to send data did not work either. Translating the curl
DATA="token=MY_TOKEN&content=record&format=json&type=flat&overwriteBehavior=normal&data=[{"id":"id1","id_complete":"0","name":"myname", "demo_complete":"0"}]&returnContent=count&returnFormat=json"
CURL=`which curl`
$CURL -H "Content-Type: application/x-www-form-urlencoded" \
-H "Accept: application/json" \
-X POST \
-d $DATA \
MY_URL
into
this.packet = { token: MY_TOKEN,
content: 'record',
format: 'json',
returnFormat: 'json',
type: 'flat',
data: [{"id":"id1","id_complete":"0","name":"myname", "demo_complete":"0"}],
};
this.headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'});
this.http.post(this.apiurl, JSON.stringify(this.packet {headers:this.headers}).subscribe(data => {
console.log('success')
console.log(data);
}, error => {
console.log(error);
console.log("Oooops!");
});
I am at beginner level when it comes to the http calls, so I am quite sure it is a silly mistake on my part. Any help or advice would be very much appreciated.

how to send curl Authorization -u of curl in node js? [duplicate]

This question already has answers here:
how to do Auth in node.js client
(2 answers)
Closed 5 years ago.
I don't know how to send the curl -u in node js i try the following code but no luck.
request({
url: "https://preview.twilio.com/HostedNumbers/HostedNumberOrders",
method: "POST",
json: true,
headers: {
"content-type": "application/json",
"Authorization": accountSid + authToken
},
json: {
"PhoneNumber": payload.phonenumber, "SmsCapability": true, "IsoCountry": payload.isocountry,
"AddressSid": address.sid, "Email": payload.email,
"FriendlyName": payload.friendlyname, "StatusCallbackUrl": "http://example.com/callback",
"StatusCallbackMethod": "POST",
},
}, function (error, response, body) {
res.json({ 'error': error, 'data': response, 'body': body });
return true;
})
this is the curl which i want to call.
curl -XPOST https://preview.twilio.com/HostedNumbers/HostedNumberOrders \
-d "PhoneNumber=+18312011484" \
-d "SmsCapability=true" \
-d "IsoCountry=US" \
-d "AddressSid=ADXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d "Email=hostedsms#twilio.com" \
-d "FriendlyName=HostedNumberOrder1" \
-d "StatusCallbackUrl=http://example.com/callback" \
-d "StatusCallbackMethod=POST" \
-u 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token'
Twilio api
Twilio supports HTTP Basic and Digest Authentication. This allows you to password protect your TwiML URLs on your web server so that only you and Twilio can access them.
See: docs
Request: http authentication
Digest authentication is supported, but it only works with sendImmediately set to false; otherwise request will send basic authentication on the initial request, which will probably cause the request to fail.
See: docs
var options = {
url: 'https://preview.twilio.com/HostedNumbers/HostedNumberOrders',
auth: {
user: username,
password: password,
sendImmediately: true
}
}
request(options, function (err, res, body) {
if (err) {
console.dir(err)
return
}
console.dir('headers', res.headers)
console.dir('status code', res.statusCode)
console.dir(body)
})
Note that you can also specify basic authentication using the URL itself, as detailed in RFC 1738. Simply pass the user:password before the host with an # sign:
var username = 'username',
password = 'password',
url = 'http://' + username + ':' + password + '#some.server.com';
request({url: url}, function (error, response, body) {
// Do more stuff with 'body' here
});

Categories

Resources