converting curl query in jquery ajax request - javascript

I have a curl command for getting json data and I want to send this request from javascript program. Please anybody can tell how to convert this curl command into jquery ajax request.
Command:
curl -H "Snapdeal-Affiliate-Id:<your affiliate ID>" -H "Snapdeal-Token-Id:<your affiliate Token>" "<URL for the chosen category>" -H "Accept:application/json"

cURL -H parameters add extra headers to the request.
jQuery.ajax have an option headers, this is a Plain JavaScript Object with the pair name/value for each header.
Then, your cURL request will translate in something like this:
$.ajax(url, {
url: "<URL for the chosen category>"
headers: {
"Snapdeal-Affiliate-Id":"<your affiliate ID>",
"Snapdeal-Token-Id":"<your affiliate Token>"
},
accepts: "application/json"
}).done(function (data) {
// code to handle succesful response
}).fail(function (data) {
// code to handle error response
});

Related

jQuery, How do I format a JSON request with authorization?

I'm new to JSON requests, cURL, etc. and I can't figure out how to correctly format a JSON request with authorization. I'm trying to call on a Spotify API and they reccomend a cURL request:
GET https://api.spotify.com/v1/search
and
curl -X "GET" "https://api.spotify.com/v1/search?q=tania%20bowra&type=artist" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ReallyLongKey"
I don't know how to use cURL and GET so I tried to use ajax:
function Search() {
$.ajax({
url: 'https://api.spotify.com/v1/search?q=Muse&type=track%2Cartist&market=US&limit=10&offset=5',
datatype: 'json',
type: 'get',
cache: false,
success: function(Data) {
//stuff
}
});
}
How do I use cURL or add authentication to the ajax method? Thanks in advance,
Justin.

data-Binary in request nodejs

I'm trying to upload a file to dropbox throug nodeJS.
This CURL request works.
curl -X POST https://content.dropboxapi.com/2/files/upload \
--header "Authorization: Bearer myToken" \
--header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false}" \
--header "Content-Type: application/octet-stream" \
--data-binary #fileName
I don't know how to translate it into javascript code.
Here's what I've accomplished so far:
var request = require('request')
var headers = {
"Authorization": "Bearer " + dropboxToken,
"Dropbox-API-Arg": {
"path": "/"+fileName, //nome sul drive
"mode": "add",
"autorename": true,
"mute": false
},
"Content-Type": "application/octet-stream"
}
var options = {
url: 'https://content.dropboxapi.com/2/files/upload',
method: 'POST',
headers: headers,
}
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
How do I include the data-binary option in this request in order to select the file to upload?
Thanks.
you can create a readstream and then pipe it to request with your current headers and options like-
fs.createReadStream('/path/to/youfile').pipe(request.post(options).on('end', (done) => { console.log('success') }));
First, if you're trying to integrate with the Dropbox API in JavaScript, we recommend using the official Dropbox API v2 JavaScript SDK, as it will do most of the work for you:
https://github.com/dropbox/dropbox-sdk-js
Otherwise, if you don't want to use the SDK, you can make the requests yourself. In this case, the --data-binary parameter is the curl parameter for supplying the data for the request to curl. curl then takes that data and puts it in the request body, which is the correct way to supply file data for a Dropbox API v2 "content-upload" style endpoint, such as /2/files/upload.
So, you should check the documentation for the HTTP client you're using for information on how to set the request body. It looks like you're using the request node module, which appears to take a body option, where you can put the request data.

Using React and axios for curl

Is it possible to make a curl request by using axios?
the curl string is:
curl -v 'https://developer.api.autodesk.com/authentication/v1/authenticate' --data 'client_id=1234&client_secret=1234&grant_type=client_credentials&scope=bucket:create bucket:read data:write data:read viewables:read' --header 'Content-Type: application/x-www-form-urlencoded' -k | jq '.'
I tried to do this:
getToken() {
axios.get({
url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
data: {
client_id: '1234',
client_secret: '1234',
grant_type : 'client_credentials',
scope: 'data:read data:viewables'
},
beforeSend: function(xhr) {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
}, success: function(data){
console.log(data)
}
})
}
But with no luck - e.g. nothing happens.
I previously used the cygwin-terminal to make the curl-request and I succesfully got the response
{
"token_type": "Bearer",
"expires_in": 1799,
"access_token": "eyJhbGciOiJIUzI1NiIsImtpZCI6Imp3dF9zeW1tZXRyaWNfa2V5X2RldiJ9.eyJjbGllbnRfaWQiOiJjWTFqcm1rQXhPSVptbnNsOVhYN0puVURtVEVETGNGeCIsImV4cCI6MTQ4NzU2NzgwMSwic2NvcGUiOlsiZGF0YTpyZWFkIl0sImF1ZCI6Imh0dHBzOi8vYXV0b2Rlc2suY29tL2F1ZC9qd3RleHAzMCIsImp0aSI6InJZcEZZTURyemtMOWZ1ZFdKSVVlVkxucGNWT29BTDg0dFpKbXlmZ29ORW1MakF0YVVtWktRWU1lYUR2UGlnNGsifQ.uzNexXCeu4efGPKGGhHdKxoJDXHAzLb28B2nSjrq_ys"
}
So, is this possible with React/axios?
In addition to the question, can I pass the received token to another curl request?
Well it's not really "a curl request". It's an HTTP request. Curl is just the tool you use to do HTTP (and other) actions via the command line.
In your HTTP request, I can see you're using axios.get(), however you're trying to do a post request (you've got a data object you're trying to send). So you should be using axios.post(). It'd be best to check out the axios page to see the syntax for HTTP posts, including how to include the data and header objects in the post.
In answer to your second question, yes you can. In the .then() section of your first axios post, you can do another axios post using the response, e.g.
axios.post(
...
).then(response => {
// do another post with response.token or whatever as the data
})
...

JQuery $.post() and curl

This is what the GroupMe API (https://dev.groupme.com/docs/v3#messages_create) asks for:
$ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN
Please assume ID is a valid group id and the token is also valid and works. How exactly would I convert that to a $.post() request and run it from the console of a browser? Here is what I have that is not working in IE when Cross Domain is enabled and it is a trusted site:
var t = {"source_guid": "frgfre", "text":"alala"};
$.post("https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN", t);
//I have also tried t.toString() as well but it didn't work
If that can't be converted (or what I have right now is correct), where would I run the first bit of code?
$.post posts the data in application/x-www-form-urlencoded format. If the API requires it to be JSON, you need to use $.ajax to override the default.
$.ajax({
url: "https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN",
data: JSON.stringify(t),
contentType: 'application/json',
processData: false
});

how to transform from curl command to ajax request

I have command to curl to server to get information
curl -v -H "Content-Type:application/json" -H "X-KGP-AUTH-TOKEN: a5a95c30274611e2ae10000c29bb7331" -H "X-KGP-APPID:id.kenhgiaiphap.kcloud" -H "X-KGP-APPVER:0.0.1" -H "X-KGP-DEVID:xxx" -H "X-KGP-DEVTYPE:xxx" http://test.kenhgiaiphap.vn/kprice/account/profile/get/token
I write ajax to handle this
$.ajax({
url: "http://test.kenhgiaiphap.vn/kprice/account/profile/get/token",
type: "POST",
cache: false,
dataType: 'json',
success: function() { alert('hello!'); },
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('X-KGP-AUTH-TOKEN','a5a95c30274611e2ae10000c29bb7331');
xhr.setRequestHeader('X-KGP-APPVER', '0.0.1');
xhr.setRequestHeader('X-KGP-DEVID', 'xxx');
xhr.setRequestHeader('X-KGP-APPID','id.kenhgiaiphap.kcloud');
xhr.setRequestHeader('X-KGP-DEVTYPE', 'xxx');
}
But I have problem is
2XMLHttpRequest cannot load http://test.kenhgiaiphap.vn/kprice/account/profile/get/token. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
and in request is
token
test.kenhgiaiphap.vn/kprice/account/profile/get
OPTIONS
(canceled)
Load cancelled
text/plain
jquery-1.7.2.min.js:2320
Script
156B
0B
1.15s
39ms
39ms1.11s
Thank for support!
This is a browser issue.
Change dataType to jsonp or add callback=? to your url:
http://test.kenhgiaiphap.vn/kprice/account/profile/get/token?callback=?
Future refer to https://stackoverflow.com/a/6396653/744255
You cannot use post in client site "Same Origin Policy issue".
Ou can use jsonp instead 'json' and change to get, pretty much following "Gabriel Santos" suggestion

Categories

Resources