Perform curl requests in javascript - javascript

Can anyone help me how to do this in javascript if it's possible?
curl \
-H 'Accept: application/json' \
-H 'Client-ID: <client_id>' \
-d'{"channel_id":<channel_id>}' \
-X POST 'https://open-api.trovo.live/openplatform/channels/id'

You can either use a child_process or convert to a fetch(or equivalent)
const exec = require('child_process').exec;
exec('curl ...', function (error, stdout, stderr) {
// handle result
})

This is JS Fetch API:
fetch("https://open-api.trovo.live/openplatform/channels/id", {
headers: {
Accept: "application/json",
"Client-Id": "<client_id>"
},
method: "POST"
})

Why you want to use JS.
You can use JQUERY Ajax:
$.ajax({
url: url,
dataType: "json",
type: "POST/GET",
async: true,
data: { },
success: function (data) {
//code
},
error: function (xhr, exception) {
//console.log err
}
});

Related

Converting cURL to Ajax and getting back Error 400

I am trying to store specific urls into jsonbox. However, I have been getting Error 400.
The curl command from the documentation is as below:
curl -X POST 'https://jsonbox.io/demobox_6d9e326c183fde7b' \
-H 'content-type: application/json' \
-d '{"name": "Jon Snow", "age": 25}'
Below is my edited code, putting in the link for jsonbox and URL as the data.
function send_request(url) {
this.url = url;
$.ajax({
url: 'https://jsonbox.io/box_89ad34d6d995aeb9ebb4',
type: 'post',
data: JSON.stringify(this.url),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
}
What am I missing or doing wrong here?
The issue seems to be the payload. Not sure why are you sending the url with your POST request. Check this working snippet:
$(document).ready(function() {
var payload = {
"name": "Maria",
"age": 78
}
$.ajax({
url: 'https://jsonbox.io/demobox_6d9e326c183fde7b',
type: 'POST',
data: JSON.stringify(payload),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
error: function(){
console.log("Cannot get data");
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How can I send a curl request from javascript?

I would like to send this
curl https://fcm.googleapis.com/fcm/send \
-H "Content-Type: application/json" \
-H "Authorization: key=<MY API KEY>" \
-d '{ "notification": {"title": "Hello world", "body": "you got a new message", "icon": "icon/path","click_action" : "page/path"},"to" : "<DEVICE TOKEN>"}'
from a js file to wherever I want. Considering the ideas you are giving me bellow, now I'm trying with this:
$.ajax({
url: "https://fcm.googleapis.com/fcm/send",
type: 'POST',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin' : '*',
'Authorization': '<APY KEY>',
'contentType': 'application/json',
},
data: {
'title': 'Hello world!',
'body': 'you got a new message',
'icon': 'icon/path',
'click_action' : 'page/path',
'to' : '<DEVICE TOKEN>',
},
success: function (result) {
alert(JSON.stringify(data));
},
error: function (error) {
alert("Cannot get data");
}
});
but I'm getting this error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present
Curl doesn't exist in JavaScript, instead you can use XMLHttpRequest. To make it even more easy, you can use jQuery to send an AJAX request.
Here is some example code:
$.ajax({
type: "POST",
url: "http://yourdomain.com/example.php",
data: {
api_key: "xxxxxxxx"
},
success: function(data) {
console.log(data);
//do something when request is successfull
},
dataType: "json"
});

How to convert cURL request to ajax with curl -d body

I'm trying to get the cURL request (working via terminal on my mac) to jQuery ajax, and I'm getting a 400 BAD REQUEST. Please let me know if you see any problems with my code. This is in an attempt to use the Oanda v20 API if that helps.
cURL via terminal (working):
body=$(cat << EOF
{
"order": {
"units": "100",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
}
EOF
)
curl \
-X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <AUTHENTICATION TOKEN>" \
-d "$body" \
"https://api-fxpractice.oanda.com/v3/accounts/<ACCOUNT>/orders"
jQuery ajax (not working):
$.ajax({
type: "POST",
url: 'https://api-fxpractice.oanda.com/v3/accounts/' + accountNumber + '/orders',
data: {
"order": {
"units": "10000",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + auth)
}, success: function(data){
console.log(data);
}
});
Obviously, auth, accountNumber, etc. are valid variables defined outside of this code.
The content-type of your request is application/json, you should add it to the request and make sure that the content itself is sent as a string (using JSON.stringify):
$.ajax({
...
contentType: 'application/json',
data: JSON.stringify({'order': { ... }}),
...
});
It might be blocked due to same-origin policy.
Have you tried with JSONP? (add dataType: "jsonp" to your ajax call)
$.ajax({
type: "POST",
dataType: "jsonp",
url: 'https://api-fxpractice.oanda.com/v3/accounts/' + accountNumber + '/orders',
data: {
"order": {
"units": "10000",
"instrument": "EUR_USD",
"timeInForce": "FOK",
"type": "MARKET",
"positionFill": "DEFAULT"
}
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + auth)
}, success: function(data){
console.log(data);
}
});
However, given that you're seemingly printing someone's account number into plain text JavaScript on the page, wouldn't it be more secure to send the CURL request from your own php file? Use Ajax to call your local file and then send the CURL request from there, and use the API's response to formulate your own JSON response to send back to your client side.

cURL to jQuery AJAX conversion

I've racked my brain over this and I cant seem to figure out the solution so ask humbly for your assistance please. I'm using the restlet client on chrome which uses a cURL command to GET json from a server. I need to convert this curl command over to AJAX, and I'll provide as much code as I'm allowed to. Could you please help me by converting this over to jQuery's Ajax?
cURL Command:
curl -i -L -X GET \
-H "Authorization:Basic base64username:base64password" \
'https://internalserverurl'
Here's what I have for my jQuery AJAX Method:
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function getData() {
$.ajax({
url: "https://internalurl",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function (data) {
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push(key + ":" + data[key] + "<br><br>");
}
}
alert(strBuilder.join(""));
$('#errordiv').html(strBuilder);
}
});
}
Thank you all for your assistance.
I said it in the comments, but you can use the $.ajax function and set your headers in the beforeSend block.
$.ajax({
url: 'https://internalserverurl',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization':'Basic base64username:base64password');
}

Mimic Curl Headers in Ajax

I'm trying to mimic this curl command to an ajax call.
curl -H 'X-Auth-Id' 'someid' http://someurl.com/api/posts
I've tried using
$.ajax({
url: 'http://someurl.com/api/posts',
type: 'get',
headers: {
'X-User-Id': userId
},
success: function(data) {
console.log(data);
}
});
But I seem to be getting an Invalid status code error, which I do not get when using curl from bash.

Categories

Resources