Signature does not match s3 GET object - javascript

I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance

Related

Cant send XMLHttpRequest in Android 11

Im using a WebView in Android studio and running it on a Physical Zebra TC52 Device which runs Android 11. In the HTML I have a button that onclick calls the getData function. The XMLHTTPRequest always returns the status 0 and the response Text is empty.
I have tried this code on https://jsfiddle.net/ and it worked fine. I dont know what the issue is
function displayData(data) {
document.getElementById('size_value').textContent = "10.5cm x 7cm";
document.getElementById('colour_value').textContent = "Red";
document.getElementById('material_value').textContent = "Metal";
document.getElementById('send_date_value').textContent = "2022-12-25";
document.getElementById('table').style.visibility = "visible";
}
function loadJSON(path, success) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('table').style.visibility = "visible";
document.getElementById('status_value').textContent = xhr.status;
document.getElementById('content_value').textContent = xhr.responseText;
if (xhr.status === 200) {
success(JSON.parse(xhr.responseText));
}
}
};
xhr.open('GET', path, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
}
function getData() {
//this will contain an API call for the data
loadJSON("https://catfact.ninja/fact", displayData);
}
I have tried the code on https://jsfiddle.net/ and it worked.
I would like to call an API and get the JSON Data in return in order to fill it into the HTML fields
You need to add internet permission to you android app:
<uses-permission android:name="android.permission.INTERNET" />
https://developer.android.com/training/basics/network-ops/connecting

How to upload a file to a node js server via HTML form?

I have a problem with uploading a file to a node server via HTML. In the page I have this input:
<input type="file" id = "csvFile" />
<input type="submit" name="submit" onclick="send_data()" />
Then I have the send_data function that looks like this:
function send_data(){
let file = document.getElementById("csvFile");
const xhr = new XMLHttpRequest();
xhr.open("GET", file, true);
xhr.setRequestHeader("Content-type", "text/csv");
xhr.onreadystatechange = () =>{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
console.log("done");
}
xhr.send();
}
Here there is the first problem, because the arrow function of the ready state never executes.
In any case, it's the first time I do something like this, so I don't know how I can make sure that my server gets the file and processes it. Can someone help me?
This should do the trick:
let file = document.getElementById("csvFile").files[0];
let xhr = new XMLHttpRequest();
let formData = new FormData();
formData.append("csvFile", file);
xhr.open("POST", '${your_full_address}');
xhr.onreadystatechange = function () {
// In local files, status is 0 upon success in Mozilla Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
var status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send(formData);
Refer: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange

rewriting a function to a boolean

hi guys I have this function:
its checking if the image URL is an actual image, but I want to change it , instead of console log I want it to return true or false,
function checkImage(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //if(statusText == OK)
{
console.log("image exists");
} else {
console.log("image doesn't exist");
}
}
}
checkImage("https://picsum.photos/200/300");
I want checkImage to return True/False instead of console logging, but when i write return true or false, that doesn't seem to work,
anyone knows why?
If the whole purpose of this function is to check if the image exists with the intent of displaying a default image I would use a much simpler approach. Why not use the following method:
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
This is described at further length here
Just change the console to callback may help u solve it
function checkImg(url,success,error){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //.if(statusText == OK)
{
success && success()
} else {
error && error()
}
}
}
Replace the Ajax with Image.onload()

Detect browser tab close without jquery and send some data to php file

I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload

Why is this JSON query not working?

I am so confused at the moment, as to why this will not work.
<div id="result" style="color:red"></div>
and
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('https://www.eobot.com/api.aspx?coin=DOGE&json=true').then(function(data) {
alert('Your Json result is: ' + data.DOGE); //you can comment this, i used it to debug
result.innerText = data.DOGE; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
It's exactly the same as: http://jsfiddle.net/RamiSarieddine/HE2nY/1/ but yet that works..
Edit: For the sake of clarity, the script is supposed to take the content at the url (within the DOGE element) and display it within
<div id="result" style="color:red"></div>
I tested it and i get below error, Which means when you try to get the json from https://www.eobot.com/api.aspx?coin=DOGE&json=true , its blocked from receiving the data due to cross browser rules.
No 'Access-Control-Allow-Origin' header
How to fix it ,
You must own https://www.eobot.com and run this script on www.eobot.com , Else you cant get the json due to cross domain policy.Ask the owner to whitelist your domain in his allow-origin header.

Categories

Resources