Xhr upload support on Cross Domain requests - upload

I have a proxy that uploads a fire to the Amazon S3 Server. This proxy is made using NodeJS and my webpage is hosted on a Tomcat server. So to make a Xhr upload I had to use Nginx to solve the cross domain issues as the both servers are on the same machine.
But using Nginx has a lot of issues so my boss asked if I can do the same thing using a Cross Domain Policy. I've made it but that is some things that I'm not being able to do. Here is my code:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {};
xhr.open('POST', self.basePath + '/upload' + file.name, true, null, null, null, true, true);
xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xhr.setRequestHeader("Connection", "close");
xhr.sendAsBinary(file.getAsBinary());
This works on a Cross Domain Request reaching the Server with the file and returning the response, but when I try to set a progress event like these:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(e) {};
xhr.upload.onprogress = function(){console.info('on progress');};
xhr.open('POST', self.basePath + '/upload' + file.name, true, null, null, null, true, true);
xhr.setRequestHeader("Accept", "application/json, text/javascript, */*; q=0.01");
xhr.setRequestHeader("Connection", "close");
xhr.sendAsBinary(file.getAsBinary());
The Cross Domain Request isn't fired ( the request uses a "OPTIONS" method instead of POST and it never reaches the server ). But, as you may think, I need the progress event to show it to the user. Does anyone knows what is happening??
Ps: All of the codes above works perfectly on a "same domain" request.
Ps2: I've tried xhr.onprogress but it is never fired ( on cross or same domain requests )
Ps3: I've tried on FF4+ and Chrome 12+
Thanks A LOT.
Thiago

I faced a similar problem before.
Solution: Add
<AllowedHeader>*</AllowedHeader>
in your CORS configuration on s3

xhr.upload.addEventListener("progress", yourUpdateProgressFunction, false);

Related

Cannot POST with ESP8266 (espruino)

I cannot make post request (get works fine) with espruino.
I've already checked the documentation and it seems pretty equal
here is my code:
let json = JSON.stringify({v:"1"});
let options = {
host: 'https://******,
protocol: 'https',
path: '/api/post/*****',
method: 'POST',
headers:{
"Content-Type":"application/json",
"Content-Length":json.length
}
};
let post = require("http").request(options, function(res){
res.on('data', function(data){
console.log('data: ' + data);
});
res.on('close', function(data){
console.log('Connection closed');
});
});
post.end(json);
The espruino console only return the 'connection closed' console.log.
The node.js server console (hosted on heroku and tested with postman) dont return anything.
Obv the esp8266 is connected to the network
What you're doing looks fine (an HTTP Post example is here), however Espruino doesn't support HTTPS on ESP8266 at the moment (there isn't enough memory on the chips for JS and HTTPS).
So Espruino will be ignoring the https in the URL and going via HTTP. It's possible that your server supports HTTP GET requests, but POST requests have to be made via HTTPS which is why it's not working?
If you did need to use HTTPS with Espruino then there's always the official Espruino WiFi boards, or I believe ESP32 supports it fine too.
you're using a package called "http" and then trying to send a request over https. You should also log out 'data' in the res.close so you can get some errors to work with.

Workbox - workbox.cacheableResponse does not work when checking for response headers

I have implemented the cacheableResponse for Workbox by checking the response header from the API.
However, it seems it does not cache API requests that have the x-is-cacheable header present on the response.
Here's how I implemented my service worker
const cacheableResponse = new workbox.cacheableResponse.Plugin({
statuses: [0, 200],
headers: {
'x-is-cacheable': true,
},
});
// APIs
workbox.routing.registerRoute(
new RegExp('https://my-api-url.here'),
workbox.strategies.networkFirst({
cacheName: 'api-cache',
plugins: [
cacheableResponse
]
})
);
I can confirm that the API response header has the x-is-cacheable: true present and it returns the status code 200.
If I remove the headers then it works, however I need to filter out the specific APIs that I need to cache.
Does anyone have an idea why this solution does not work?
So, I just discovered on Github that my issue is somewhat related with CORS and in order for the X-Is-Cacheable to work I also needed to add Access-Control-Expose-Headers: X-Is-Cacheable in our API response (it may vary with different codebase so please refer to your API framework on how to add response header in to your API).
reference: https://github.com/GoogleChrome/workbox/issues/2051

Shopify API HTTP POST redirecting instead of POSTing

I have code (Classic ASP) which was recently working POSTing orders to Shopify but has now stopped POSTing and either creates an error "A Redirection problem has occurred" or redirects to the admin area of the Shopify site, depending on which XMLHTTP component I employ. The code below still works on older OS but not on Server 2016 where I am working.
I can't find much on Google but there was an indication in the Shopify Forum that the problem was a result of cookies (I have set none) and that this is overcome by sending a header containing X-Shopify-Access-Token:. I tried this using the "Authorize" setRequestHeader but it made no difference, or I got the syntax wrong or something. I used
xmlhttp.setRequestHeader "Authorization","X-Shopify-Access-Token=<token>"
Below is the code that worked a few weeks back. Variable jsondata contains valid JSON to send to create an order.
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.3.0")
xmlhttp.Open "POST", "https://<api key>:<passowrd>#<sitename>.myshopify.com/admin/orders.json", false, "<api key>", "<password>"
xmlhttp.setRequestHeader "Content-Type", "application/json; charset=utf-8"
xmlhttp.setRequestHeader "Content-Length", Len(jsondata)
xmlhttp.Send jsondata
Set xmlhttp = nothing
I expect a POST and a JSON order response but this is not happening - just a redirection to https://<sitename>.myshopify.com/admin. Any ideas anyone?

All requests blocked by CORS policy on development

I have a Rails API with a React client side. I have had everything in the app setup for a long time now and today while I was working on it I suddenly started getting the error:
Access to XMLHttpRequest at 'http://localhost:3000/api/v1/user/authed'
from origin 'http://localhost:8000' has been blocked by CORS policy:
The value of the 'Access-Control-Allow-Origin' header in the response
must not be the wildcard '*' when the request's credentials mode is
'include'. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
Now none of the requests in my application work at all.
The request does go through from the React app to the Rails API and the Rails API responds properly as well (I can see this in the terminal) but nothing actually happens on the Client side because I am assuming it gets blocked for the CORS reason.
Is there something I can do to fix this? Could it be that some package is somehow updated on my system and different from the project so now it breaks?
URL to make request to:
const ENDPOINT = '/api/v1',
PORT = 3000,
URL = window.location.protocol + '//' + window.location.hostname + ':' + PORT + ENDPOINT;
The request
$.ajax({
url: URL + '/' + resource,
type: verb,
data: params,
xhrFields: { withCredentials: true }
})
.done(callback)
.fail(errcallback);
Request functions have the format:
static get(resource, params, callback, errcallback) {
API.send('GET', resource, params, callback, errcallback);
}
If your API doesn't require credentials you should remove withCredentials: true.
More about withCredentials:
The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

XMLHttpRequest Post Method - Headers are stopping function

I'm trying to send an XMLHttpRequest object to my Rails server but the headers are causing my function to stop. Here are my observations:
When I comment out the 3 lines of code that set the headers, then xhr.readyState will eventually equal 4 (alert boxes within the anonymous function fire off).
If any one of the 3 header lines are uncommented, then the xhr object never changes state (none of the alert boxes ever fire off).
function saveUserProfile(){
var user_email = $('#userEmail_box').val();
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200)
{
alert("Yes: " + xhr.readyState);
}
alert("No: " + xhr.readyState);
}
var method = 'POST';
var params = 'userEmail=user_email';
var url = 'http://localhost:3000/xhr_requests.json';
var async = true;
//Need to send proper header information with POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.open(method, url, async);
xhr.send(params);
}
My three questions are:
What do I need to change in the code above in order to send data through the POST method?
I'm under the impression that the POST method requires some headers to be sent but am not clear about which ones though "xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');" seems to be one that is often mentioned in references. Can somebody help me understand a) why headers need to be sent and b) which ones need to be sent?
I'm using a rails server and am developing locally. Ultimately, this code will be executed on the client side of a mobile device which will go to a hosted rails server for passing and receiving data. Are there limitations with using the POST method with a rails server? Keep in mind that I plan to use JSON when sending information to the client from the server.
Thanks!
UPDATE: The headers should come AFTER the opening the xhr request but BEFORE sending it:
xhr.open(method, url, async);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length', params.length);
xhr.setRequestHeader('Connection', 'close');
xhr.send(params);
Hope this post saves somebody else 4 hours.
Does your web page with the JavaScript code also live on localhost:3000? If not, this is considered a cross-domain request, and your server will need to return special headers. So you have two options:
1) Host the web page on the same domain as the server, which will make this a same-domain request.
2) Have your server return the appropriate CORS headers. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Resources