Using React and axios for curl - javascript

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
})
...

Related

how to put --data in GET method ? since GET not recieving body parameter

i've given the api endpoint with GET method but i think it needs a body, when i test it on postman it works fine but in react native when i try to fetch it it shows error [TypeError: Body not allowed for GET or HEAD requests]
my backend partner send this curl, how to use the --data since GET are not recieving any body
curl --request GET \
--url http://base_url/api/v2/order/all \
--header 'Content-Type: application/json' \
--cookie 'token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwaG9uZU51bWJlciI6IjA4ODc3NzA5MjIxIiwidXNlcm5hbWUiOiJGbG8iLCJpYXQiOjE2NTEwMzIxNTYsImV4cCI6MTY1MTA3NTM1Nn0.JkwTPvjig7bd8Q27MvZ7DsUCz68Qyzh3EctFTRh-m0E; connect.sid=s%253AgtaL-l_60sBGAdEhTiHspbzX3rBBiEFg.O5z0JBi7Oqo1UXSZOxQckm2FNhG3A%252BWZod951CC5Cys' \
--data '{
"userId":"79025884",
"limit":10,
"page":1
}'
this is my function
function GetActivity() {
const url = APIConfig.SERVER.ORDER + "/all";
fetch(url, {
method: "GET",
headers: { "content-type": "application/JSON" },
body: JSON.stringify({
userId: "79025884",
limit: 10,
page: 1,
}),
})
.then((response) => response.json())
.then((data) => {
console.log("GetActivity Order:", data);
setOrderList(data.data);
})
.catch((error) => {
console.error("Error:", error);
});
}
For a GET request, any parameters you want to pass to the API end point will need to be sent as part of the url I believe.
E.g. http://example.com/id/1 (where 1 is the dynamic value for the ID parameter)
I think the error you are seeing is because your trying to set a "body" value for a get request, which would be used with a POST request instead for example.
The same problem I faced several days ago, and I made some research about it. I can say that even though it is possible to use get method with body in postman you can't use get method with body with fetch or axios, because body is not allowed. And I think you should allow post method in your backend if your want to send data. You can read in depth about it here.
You need to add it to the URI or the HTTP request headers depending on the data. Usually URI path for hierarchical resource identification data and URI query for non-hierarchical. There are standard HTTP headers for many things including pagination. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests They are for byte ranges, but you can use custom units like pages. Another way is doing pagination with URI.
GET https://example.com/api/v1/orders/by-user-id/79025884/?page=1&limit=10
GET https://example.com/api/v1/orders/by-user-id/79025884/ "Range: items=1-10"

Unable to get access token for linkedin using axios

I am trying to get access token following the steps described in Linkedin Oauth. I am trying to perform step 2 in the process to get an access token. I am using Axios for the POST request. Here is the code I am using (The client secret and id is not real for security reasons):
const axios = require('axios');
const qs = require('qs');
axios({
method: 'post',
url: 'https://www.linkedin.com/oauth/v2/accessToken',
data: qs.stringify({
grant_type: 'authorization_code',
code: 'AQSow7V6s2F2koWzIsnVKcQGt_cHtsM1F3FHZOrEV0UY1KIFkWiFJpi8dt1NtjuZMOO6-NStoCjTf58awk6GBcH2XQRctt7IBtel4Oeop5yVIBqiedk8qxlIlbkMxlfGg1gCVoupXL6xUc3-jegKYDPSe0rl4mygdpIzGdej2_hhJ827vJcojtvaMXCCGw',
redirect_uri: 'https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Ftttrrr878',
client_id: '99blt2z20qlm3d',
client_secret: 'fGGgdqqcx5t3cRfw'
}),
headers: {
content-type: 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(result => {
console.log(result.data);
}).catch(error => {
console.log(error);
});
I get the following error when I run the code even after making sure that the code is not expired (before the 30 min expiration time):
data: {
error: 'invalid_redirect_uri',
error_description: 'Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists'
}
However when I do the same thing using curl in the command line as follows, I am able to get the access code:
curl -ik -X POST https://www.linkedin.com/oauth/v2/accessToken \
-d grant_type=authorization_code \
-d code=AQSow7V6s2F2koWzIsnVKcQGt_cHtsM1F3FHZOrEV0UY1KIFkWiFJpi8dt1NtjuZMOO6-NStoCjTf58awk6GBcH2XQRctt7IBtel4Oeop5yVIBqiedk8qxlIlbkMxlfGg1gCVoupXL6xUc3-jegKYDPSe0rl4mygdpIzGdej2_hhJ827vJcojtvaMXCCGw \
-d redirect_uri=https%3A%2F%2Fwww.linkedin.com%2Fcompany%2Ftttrrr878 \
-d client_id=99blt2z20qlm3d \
-d client_secret=fGGgdqqcx5t3cRfw
Any idea why this is happening? Is it somehow related to this
issue ?
Your code looks correct. The issue is because you are url encoding the redirect_uri parameter, remove that and it should work.
You only need to url encode the redirect_uri parameter when doing the initial request for the access code from the browser.

Need help converting cURL command to Javascipt

I am trying to get recipe nutritional information from Edamam API. In the API docs, the cURL command is:
curl -d #recipe.json -H "Content-Type: application/json" "https://api.edamam.com/api/nutrition-details?app_id=${YOUR_APP_ID}&app_key=${YOUR_APP_KEY}"
I am using Axios and Javascript to try to access the API with a Post command:
import axios from "axios";
var postData = './recipe.json'
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',}
};
axios.post('https://api.edamam.com/api/nutrition-details?app_id=XXXXXXXX&app_key=XXXXXXXXXXXXXXXXXXXXX', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
I receive a 400 error back. Any thoughts on what I need to do to make this work would be appreciated.
postData needs to be a string of JSON.
You appear to be passing it a string containing a filename.
You might want to read './recipe.json' with axios.get() to fetch the data from it.
In your cURL the option -d #recipe.json is sending the content of the file recipe.json
But, In your Code postData = './recipe.json', You are just passing the name instead of reading it.
First you need to read the data from recipe.json,Then you need to send it through request.

cURL command works, but Fetch API call returns 200 with 400 validation error in Response Payload

Having a huge issue I came across in sending a POST request using Fetch to get a URL shortened.
I am good and able to do a POST request by cURL command to this url shortener API:
Curl command
curl -d 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch' http://fakeurlforexample/api/shorten/
Response
{"url": "https://fakeurlforexample/BdzfM3", "long_url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", "name": "BdzfM3"}
And I get this great response payload from the API.
But when I do this by Fetch with this code I provided below, I get a 200 OK and in the response payload I have a 400 validation error that I am missing the API key.
However, the request payload in the developer console shows that the parameters were passed on properly to the API (I think...)
{"api_key":"xxxxxxxxxxxxxxxxx","url":"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"}
Here is my code:
let get_url = 'http://fakeurlforexample.com/api/shorten/';
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
fetch(request)
.then(function() {
console.log(request);
console.log(request.url);
})
Does anyone see the mistake I am making here?
Been beaten down by this for across hours upon hours this week now. Thanks for any help and assistance! And no, I can't easily transition the code to axios as it is right now. This is a demonstration so I'm really just trying to get it to work.
From the curl manpage Options section on -d, --data <data>:
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
Whereas with your request, you are sending a JSON object (Content Type: application/json):
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
Since you know the API endpoint accepts application/x-www-form-urlencoded because the curl request succeeds, you can set the content type as application/x-www-form-urlencoded and send the body as a string:
let request = new Request(get_url, {
method: 'POST',
headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
body: 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'
});
Maybe its because you are defining headers 2 times.

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.

Categories

Resources