How to send curl request in react/javascript using fetch? - javascript

I want to make a request..This is the curl request
curl --location --request POST '2.2.2.22:343/sudun/cars' \
--header 'Authorization: Bearer sdswmaiqwasae*********' \
--header 'Content-Type: application/json' \
--data-raw '{
"user": "sdsffwefwefwssdsds",
"numberofunits": 4,
"price": 0
}'
This is the way I am doing.
const url = "2.2.2.22:343/sudun/cars";
const options = {
headers: {
"Authorization": "Bearer sdswmaiqwasae*********",
"Content-Type": "application/json"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
It is not working...I know i have not added --data-raw part ...I don't know how to do that..

you can try like this if you are using fetch.
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer sdswmaiqwasae*********");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"user": "sdsffwefwefwssdsds",
"numberofunits": 4,
"price": 0
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("2.2.2.22:343/sudun/cars", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Related

Post for with header (according to CURL sample)

I need to post a form with a header, the CURL of that is
curl -X POST "URL" -H "accept: application/json" -H "token: TOKEN VALUE" -H "Content-Type: application/json" -d "{ \"amount\": 1000, \"expireInSeconds\": 0, \"factorNumber\": \"string\", \"redirectUrl\": \"string\"}"
I did it like below, but can't add header (-H) to it
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", URL);
form.setAttribute("target", "_self");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "amount");
hiddenField.setAttribute("value", "1000");
form.appendChild(hiddenField);
....
....
document.body.appendChild(form);
form.submit();
The problem is that to send header for it (token)
you need to use AJAX request with headers using the fetch API, setting the appropriate headers for accept, token, and Content-Type.
const url = 'URL';
const token = 'TOKEN VALUE';
const data = {
amount: 1000,
expireInSeconds: 0,
factorNumber: 'string',
redirectUrl: 'string'
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json',
'token': token,
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

Implementing Twilio Api call from a CURL example to js returns status code of 200 but does not seem to update data

I am trying to update my sim fleet name and sim unique name without any success
const url = `https://supersim.twilio.com/v1/Sims/${sid}? fleet=${fleet}&uniqueName=${uniqueName}`;
const resp = await fetch(url, {
method: "POST",
headers: new Headers({
Authorization: auth.twilioAuth,
"Content-Type": "application/x-www-form-urlencoded",
}),
body: new URLSearchParams({
Iccid: iccid,
}).toString(),
});
I get a 200 response with my sim object as follows
account_sid: "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
date_created: "2022-01-08T21:05:00Z"
date_updated: "2022-01-08T21:05:00Z"
fleet_sid: null //did not update
iccid: "XXXXXXXXXXXXX"
links: {billing_periods: 'https://supersim.twilio.com/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXX/BillingPeriods'}
sid: "HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
status: "new"
unique_name: null //did not update
url: "https://supersim.twilio.com/v1/Sims/HSXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Twilio documentation
and this is what their CURL example website says
curl -X POST https://wireless.twilio.com/v1/Sims/DEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
--data-urlencode "CallbackMethod=POST" \
--data-urlencode "CallbackUrl=https://sim-manager.mycompany.com/sim-update-callback/AliceSmithSmartMeter" \
--data-urlencode "Status=active" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
You should send the parameters you want to update in the body of the request, not in the query parameters. Also note that the parameter names are in Pascal case. Try this:
const url = `https://supersim.twilio.com/v1/Sims/${sid}`;
const resp = await fetch(url, {
method: "POST",
headers: new Headers({
Authorization: auth.twilioAuth,
"Content-Type": "application/x-www-form-urlencoded",
}),
body: new URLSearchParams({
Iccid: iccid,
Fleet: fleet,
UniqueName: uniqueName
}).toString(),
});

Convert curl request with array of objects to JS axios or fetch request

i'm trying to convert this request :
curl https://api.stripe.com/v1/payment_links \
-u sk_test_dsgsdgsdgsdgsdyhwetdshsdhsdhsdhsdh: \
-d "line_items[0][price]"=price_1K7o9TFRZ3JYnODMxojDKSWp \
-d "line_items[0][quantity]"=1
to axios request :
My array
const arrayOfPrices = [
{ price: 'price_1K7nrWFwZ3JYnODMD6Bb3SEy', quantity: 1 },
];
I have tried :
console.log(
new URLSearchParams({
arrayOfPrices,
})
);
return axios({
method: 'post',
url: 'https://api.stripe.com/v1/payment_links',
headers: {
Authorization: `Bearer ${process.env.STRIPE_PUBLIC_KEY}`,
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: new URLSearchParams({
line_items: arrayOfPrices,
})
})
.then((res) => res.data)
.catch((err) => {
console.log(err.response.data);
return { status: 'fail', message: err.message };
});
And more different sets but it doesn't work.

git api returning 401 unauthorized error when doing axios call but curl returns 200

axios call to git api returns 401, but curling the same url with the same headers returns 200 with the correct data, anybody know why?
Axios call returns 401
let headers = {
"Authorization": "token abc",
"Accept" : "application/json",
"Content-Type": "application/json"
}
await axios.get("SOME_GIT_API_URL", headers)
.then((data) => {
console.log(data.data)
})
.catch((err) => {
console.log(err)
})
Curl returns 200
curl --location --request GET "SOME_GIT_API_URL" --header 'Authorization: token abc'
On axios, header key must be inside the object. Your header variable not included that 'header' as key. Example :
// header inside an object
const headerObject = {
header: {
"Authorization": "token abc",
"Accept" : "application/json",
"Content-Type": "application/json"
}
}
await axios.get("SOME_GIT_API_URL", headerObject)
.then((data) => {
console.log(data.data)
})
.catch((err) => {
console.log(err)
})

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

Categories

Resources