Post for with header (according to CURL sample) - javascript

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

Related

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

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

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.

How to make an encoded POST request using axios?

I am trying to create a POST request in my reactjs app based on the following API request example:
Example API request
curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I'm supposed to be base64 encoding the text following "Basic" within the header.
How do I create this request in javascript using axios? This is what I have so far:
async componentDidMount() {
const encodedString = new Buffer('1ff56abe7792f426ea41a771d707d6690:1b2cca2dedd3949b0a6c5e1582446c9c5').toString('base64');
const [initSpotResponse] = await Promise.all([
axios.post('https://accounts.spotify.com/api/token', { headers: { 'Authorization': `Basic ${encodedString}` } })
]);
}
How do I include the "grant_type=client_credentials" part?
According to axios’ README, this is the Request method aliases for POST requests
axios.post(url[, data[, config]])
axios.post('https://accounts.spotify.com/api/token',
{ data: { grant_type: ‘client_credentials’} },
{ headers: { 'Authorization': `Basic ${encodedString}` } }
)
You could also do
const options = {
url: ‘https://accounts.spotify.com/api/token',
method: 'POST',
headers: { 'Authorization': `Basic ${encodedString}` },
data: { grant_type: ‘client_credentials’}
};
axios(options);

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 Post Method to implement customized headers and with token value

I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});

Categories

Resources