Fetch cURL request using React - javascript

I have a GET curl request
curl -X GET "http://localhost:8000/get/folder" -H "accept: application/json" -H "path: /"

Something like this should work.
fetch('http://localhost:8090/get/directory', {
headers: {
'Accept': 'application/json',
'Path': '/',
}
})
.then(response => response.json())
.then(json => console.log(json));
You can call this from in a useEffect() in your React app, for example. Or componentDidMount if it is a class component.

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.

Replicate curl with fetch function in js

I have an application that returns a buffer with a Http request. When I run curl in my terminal I get a proper response:
Curl:
curl -s -X GET \ "url" \ -H "authorization: Bearer token" \ -H "content-type: application/json"
Response:
Pendiente now has [{"Key":"73ef53d2848708ae3288db3afb69ee85a663eba2ab147e83494f65585d171a2d","Record":{"cantidad":"100","docType":"fabricacion","estado":"Pendiente","id":"73ef53d2848708ae3288db3afb69ee85a663eba2ab147e83494f65585d171a2d","mercado":"dercadona","owner":"jose","producto":"manzanas","usuario":"jose"}},{"Key":"9b2d52becf9620971c7fd31c54b817533157cb2c7186dd3835f4c502742418b5","Record":{"cantidad":"200","docType":"fabricacion","estado":"Pendiente","id":"9b2d52becf9620971c7fd31c54b817533157cb2c7186dd3835f4c502742418b5","mercado":"mercadona","owner":"jose","producto":"peras","usuario":"jose"}}] after the move
I am trying to get the json part from that response with fetch using js (the fetch goes inside another fetch). I've tried different methods but I can't manage to get it properly
return fetch(url_get_tx,{
method: 'get',
headers: {
'Content-type': 'multipart/form-data',
'authorization': 'Bearer '+data.token
}
}
.then(function(data) {
var reader = data.body.getReader();
return reader.read()
console.log("here");
console.log(typeof(reader));
console.log(reader);
})
Many thanks
return fetch(url_get_tx,{
method: 'get',
headers: {
'Content-type': 'application/json'
'authorization': 'Bearer '+data.token
}
})
.then(function(data) {
return data.json()
}).then(result => console.log(result))

Axios not working for accessing getpocket api

I can make the oauth request using curl but using axios I get a error about missing consumer key
X-Error
Missing consumer key.
This happens in the OPTIONS phase of making the request.
axios({
method: 'post',
url: 'https://getpocket.com/v3/oauth/request',
data: {
'consumer_key': 'xxxx-xxxxxxxxxxxxxxx',
'redirect_uri': 'http://localhost:8080/'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
Here is the curl request
curl https://getpocket.com/v3/oauth/request --insecure -X POST -H "Content-Type: application/json" -H "X-Accept: application/json" -d "{\"consumer_key\":\"xxxx-xxxxxx\",\"redirect_uri\":\"http://localhost:8080/\"}"
Try adding the headers to your request for it to accept json:
axios({
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
url: 'https://getpocket.com/v3/oauth/request',
data: {
'consumer_key': 'xxxx-xxxxxxxxxxxxxxx',
'redirect_uri': 'http://localhost:8080/'
}
});

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.

Categories

Resources