ReactJS: fetch function - Is it possible to make a PUT request? - javascript

This is how I currently make a PUT request:
var data = {
'Content-Type': 'application/json',
'number': 'TEST12345'
}
var post = {
"number": "TEST12345",
"parameters":
{
"START_NUMBER" : {
"value": 5,
"effectiveDate": "2016/01/01 10:10"
}
}
}
var myInit = {
method: 'POST',
mode: 'cors',
headers: data,
body: JSON.stringify(post)
};
fetch('http://localhost:8080/form/upload/post/save', myInit)
.then(result=>{console.log(result.json())})
So I was wondering if it's possible to do the same but for a PUT request? If so how can I go about doing so?

Related

How to construct and Perform a transaction on Tezos blockchain

I'm trying to construct, sign and broadcast a transaction on the tezos blockchain.
Here is my current code
const rpcUrl = "someTestnetRPC";
//generate private key
// get information about the most recent block
//reveal status
//reveal operation
//can't quite figure out how to make this reveal transaction, this is the data
data: {
branch: mostRecentBlock,
contents: [
{
kind: "reveal",
fee: "1",
public_key: TezBridgeCrypto.crypto
.getKeyFromSeed(random_seed)
.getPublicKey(),
gas_limit: "10500",
storage_limit: "0",
},
],
}
//I don't know the url to send this request to.
let binaryFromRpc = await axios({
method: "post",
url: `${rpcUrl}/chains/main/blocks/head/helpers/forge/operations`,
data: {
branch: mostRecentBlock,
contents: [
{
kind: "transaction",
source: sourceAddr,
fee: "1",
counter: (Number(counter.data) + 1).toString(),
gas_limit: "10500",
storage_limit: "0",
amount: "1",
destination: "tz1biFoRp3n9X2r4o3sgcqRLkXAXce7hpPLp",
},
],
},
headers: {
"Content-type": "application/json",
},
});
const signature = Buffer.from(
ed25519.Sign(
Buffer.from(await blake2b(`0x03${binaryFromRpc.data}`, 256), "utf-8"),
Buffer.from(random_seed, "utf-8")
)
).toString("hex");
const injectionData = `${binaryFromRpc.data}${signature}`;
await axios({
method: "post",
url: `${rpcUrl}/injection/operation?chain=test&async`,
data: injectionData,
headers: {
"Content-type": "application/json",
},
});
When I send this request the final injection goes through, no failure message, no content in the returned data and I can't quite figure out what I'm doing wrong.

Request in javascript (from python)

I have attempted to create a request in javascript, that has previously worked using python just fine.
the following is an accurate representation of the code I used to post the request with python:
url = 'https://website.com/api/e1'
header = {
'authorization': 'abcd1234'
}
payload = {
'content': "text",
}
r = requests.post(url, data=payload,headers=header )
This (above) works just fine in python.
now what I did in javascript is the following:
payload = {
"content": "this is text",
};
fetch("https://website.com/api/e1", {
method: "POST",
headers: {
"authorization":
"abcd1234",
},
body: JSON.stringify(payload),
});
but this is returning the error
400- Bad request
When using data parameters on python requests.post, the default Content-Type is application/x-www-form-urlencoded(I couldn't find it on the document, but I checked the request. If you know, please leave a comment).
To achieve the same result with fetch, you must do as follows.
const payload = {
'content': 'this is text',
};
fetch('https://website.com/api/e1', {
method: 'POST',
headers: {
'authorization': 'abcd1234',
},
body: new URLSearchParams(payload),
});
You don't need to do this body: JSON.stringify(payload), rather you can simply pass payload in body like this body:payload

React axios data type issue

I have the following submit method:
submitForm(e) {
e.preventDefault();
var token = document.getElementsByTagName("meta")[0].getAttribute("content");
var form = document.querySelector('.form');
if(navigator.onLine && JSON.parse(localStorage.getItem('candidates'))) {
axios({
url: '/save-data',
method: 'POST',
contentType: 'application/json',
data: {
"candidates": localStorage.getItem('candidates')
},
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
}
}).then(function(response) {
console.log(response);
})
.catch(function(e){
console.log(e);
});
}
else {
var singleCandidate = serialize(form, { hash: true });
var fromStorage = localStorage.getItem("candidates");
if (fromStorage) {
var parsedFromStorage = JSON.parse(fromStorage)
parsedFromStorage.push(singleCandidate)
localStorage.setItem("candidates", JSON.stringify(parsedFromStorage));
}
else {
localStorage.setItem("candidates", JSON.stringify([singleCandidate]));
}
}
}
it loads data from local storage and submits it if there is data and connection at the same time.
However there is something that doesn't work with the following:
data: {
"candidates": localStorage.getItem('candidates')
},
if I do:
data: {
"candidates": [
{
"name": this.state.firstName,
"email": this.state.email,
"university": this.state.university,
"degree": this.state.degree
}
]
},
I get a positive response, form data gets submitted. However I have to submit this value (localStorage.getItem('candidates')) and when I do that I get the following:
Should "localStorage.getItem('candidates')" be changed to another format?

Image size (.bin) getting doubled while generating it via AJAX call

I am trying to generate .bin file from from REST API written in Swing from AngularJS.Following is the code.
var options = {
url: 'http://example.com/imageAPI',
method: 'POST',
headers: {
'Authentication': headerAndPostParams[0],
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
},
responseType: 'arraybuffer',
data: {
uniqueId: headerAndPostParams[1],
imageName: headerAndPostParams[2],
clientMacAddress: headerAndPostParams[3]
}
};
return $http(options).then(function(sucessResponse) {
if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
download(sucessResponse.data, "image.bin", "application/octet-stream");
return true;
}
return false;
});
Here are the response headers
Access-Control-Allow-Origin: http://localhost:8080
Content-Disposition:attachment;filename=cns3xxx_md_2.6.9_ac_aa_33_dd_aa_35.bin
Content-Length :7864320
Content-Type :application/octet-stream
Date :Tue, 18 Apr 2017 06:38:35 GMT
Vary :Origin
access-control-allow-credentials: true
Above code is working fine.But the issue is Image sent from API is of size 7.5 MB and the image generated from my UI side is of size 13.5 MB. Is there any decoding that we have to perform before giving it to donwload function. (NOTE: download is the function from donwload.js library.)
Found the solution. Actually $http service by default change the response to text. That doubles the size of image. To avoid it we need to add following parameter.
responseType: "blob"
$http({
url: 'http://example.com',
method: 'POST',
responseType: "blob",
headers: {
'Authentication': headerAndPostParams[0],
'Content-Type': 'application/json',
'Accept': 'application/octet-stream'
},
data: {
uniqueId: headerAndPostParams[1],
imageName: headerAndPostParams[2],
clientMacAddress: headerAndPostParams[3]
}
}).then(function(sucessResponse) {
if (sucessResponse.data != "" && sucessResponse.data.responseCode === undefined) {
var blob = new Blob([sucessResponse.data], {
type: "application/octet-stream"
});
download(blob, headerAndPostParams[2]);
return true;
}
return false;
}, function(response) {
return false;
});

How to set headers in Ajax call?

I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.
you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference
There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})

Categories