How do you express it using the fetch API in JavaScript? - javascript

Now, I POST image data using ajax(jquery) as follows. The image is a File object.
async function postImage({ image }) {
const result = await $.ajax({
method: 'POST',
url: '/api/images',
dataType: 'json',
data: image,
processData: false,
async: true,
headers: {
'Content-Type': 'application/octet-stream',
},
});
return result;
}
The result that return object is {id: imageID}.
How can I express this using the Fetch API? I couldn't get the result even if I did the following.
const result = await fetch('/api/images', {
method: 'POST',
body: image,
headers: {
'Content-Type': 'application/octet-stream',
},
});
return result;

fetch() returns a promise to a Response object, and that has a json() method which returns another promise to the parsed response JSON.
const response = await fetch('/api/images', {
method: 'POST',
body: image,
headers: {
'Content-Type': 'application/octet-stream',
},
});
const result = await response.json();

Related

Nodejs create diffrent post request

I’ve the following code which works when using standalone request (not promise all) , but I don’t know how can I send two request with different form data properties (see aaaa/bbbb exmaple)
e.g. this is what I need to pass for the first request (different scope)
formData.append('grant_type', 'client_credentials');
formData.append('scope', ‘aaaa’);
And this is to the second request (in the promise all)
formData.append('grant_type', 'client_credentials');
formData.append('scope', ‘bbbbb');
This is the code:
let [res1,res2] = await Promise.all([axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData.getHeaders()
},
data: formData
},
{
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]’,
...formData.getHeaders()
},
data: formData
}
)])
console.log(res1.data.access_token)
Could I append it inline for each request? I try to put an object with those properties and it doesn't compile
is there a way to do something like this
{
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]’,
...formData.getHeaders()
},
data: formData.append([{
'grant_type': 'client_credentials'
},{
'scope': 'aaaa`
}])
}
update:
I've tried to do something like
let [res1, res2] = await Promise.all([
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formA.getHeaders()
},
data: formA
}),
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formB.getHeaders()
},
data: formB
})
])
console.log(res1.data.access_token)
function formA() {
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'aaaa');
return formData
}
function formB() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'bbbb');
return formData
}
Which doesn't work, now if I create the object inside like it works but the code is ugly, is there a better way to achieve this
function formB() {
let formData = new FormData();
formData.append('grant_type', 'client_credentials');
formData.append('scope', 'bbbb');
return formData
}
You're nearly there.
The main problem is that the axios function needs to be called multiple times in the Promise.all function.
With the above solved, my last recommendation is to make separate form-data objects for each request.
For example:
var formData1 = getFormDataObjectSomehow()
var formData2 = getAnotherFormDataObjectSomehow()
let [res1, res2] = await Promise.all([
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData1.getHeaders()
},
data: formData1
}),
axios({
method: 'post',
url: 'https://oauth2.md/oauth2/token',
headers: {
'Authorization': 'Basic [userpassword]',
...formData2.getHeaders()
},
data: formData2
})
])
console.log(res1.data.access_token)
EDIT:
And don't forget to handle errors thrown from the axios requests. Either add .catch() block to your Promise.all or use a try/catch guard.

Javascript Fetch Body JSON List

I am trying to make a post request and getting this exception:
"unsupported BodyInit type"
I think the issue is with the body of the request. phoneNumbers takes on the form phoneNumbers = ["1234567890", "1234567891"] (i.e. a list of strings). I tried to do JSON.stringify(phoneNumbers) as the body, but that seems to return "[]", even if the list is not empty.
export async function findUsersByPhoneNumbersNotFollowing(userId, phoneNumbers) {
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: phoneNumbers,
};
const response = await authfetch(`${API_URL}/following/recommendations/${userId}`, reqConfig);
if (response.error) {
throw new Error(response.error);
}
return response;
}
Where am I going wrong? The API endpoint is expecting List<String> (using spring framework, and the controller method takes this param in annotated #RequestBody)
Try sending a JSON Object instead a plain array:
const reqConfig = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
paramName: phoneNumbers
}),
};
Replace paramName for the name you are expecting on your API endpoint.

Converting fetch PUT request into axios request

I have been using fetch on the frontend to make a PUT request. My code looked like the following:
fetch(url, {
headers: {
'content-type': 'png',
},
method: 'PUT',
body: file,
})
I am trying to write the same using axios but doesn't seem to be working
await axios.put(url, {
data: {
body: file
},
headers: {
'content-type': 'png',
},
})
Take a look at the axios.put signature:
axios.put(url[, data[, config]])
The second argument is treated as data, so your headers end up as part of the request body.
Further, data: { body: file }, is redundant. axios.put()'s data argument is already treated as body.
So you can either do:
await axios.put(url, file,
{
headers: {
'content-type': 'png'
}
}
)
or:
await axios.put(url, {},
{
data: file,
headers: {
'content-type': 'png'
}
}
)
Or, for even more resemblance with fetch API,
await axios(url,
{
method: 'PUT',
data: file,
headers: {
'content-type': 'png'
}
}
)

How to send a rest PUT request in angular passing body

I need to send a rest request to a web server, I am using this code :
var getData = function(...) {
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': ...,
'token': ...,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: {"...":"...","...":"...","...":"...","...":"...",
"...":"....","....":"...",
"datefrom":"2017-01-01","dateto":"2017-10-20"}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
The problem is that I am receiving error 400 bad request, What should I do?
The request works on Postman With this structure
https://i.stack.imgur.com/BBrwF.jpg
https://i.stack.imgur.com/NbQuO.jpg
Should it be a problem of how Am I passing the data object ?
That's how I implemented the $httpParamSerializerJQLike, it it Correct?
app.factory('statistics', function($http,$httpParamSerializerJQLike) {
var getData = function(loginId,token,id,dataInizio,dataFine,periodo,selezione) {
// Angular $http() and then() both return promises themselves
var data = '{"datefrom":"2017-01-01","dateto":"2017-10-20"}';
alert(data);
return $http({
method: "PUT",
url: getStatistics,
headers: {
'loginId': loginId,
'token': token,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: { 'data': $httpParamSerializerJQLike(data)}
}).then(function(result){
var dataString = JSON.stringify(result.data);
alert(result.data);
return result.data;
});
};
return { getData: getData };
});
you're sending an x-www-form-urlencoded body, but it contains a single parameter named data, containing JSON.
You thus need
data: $httpParamSerializerJQLike({data: angular.toJson(data)})

Get data from ajax request to Angular

I have 2 requests
$.ajax({
type: "POST",
url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token",
data: "grant_type=client_credentials",
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
success:function(data){
console.log(data);
getData(data.access_token);
}
})
function getData(acess_token){
$.ajax({
type: "GET",
url: "http://sandbox.gasvisor.com/api/v2/gobjects/search/withinRadius?longitude=24.711117&latitude=48.922633&radius=10",
headers: {
'Authorization':'bearer'+acess_token },
success:function(data){
console.log(data);
}
})
}
They return json from server. I need to get data from Json file to my Angular listing. Pls help me.
Here is a simple example for one of your call:
$http({
method: 'POST',
url: 'http://sandbox.gasvisor.com:9988/uaa/oauth/token',
data: 'grant_type=client_credentials',
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization':'Basic SVRXRV9XRUJfQVBQOml0d2VfY2xpZW50' },
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
$scope.response = response;
}, function errorCallback(err) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.error = err;
});

Categories

Resources