Call HTTP (non SSL/HTTPS) REST from Firebase hosted site, using XMLHttpResponse - django

I am trying to build a Firebase hosted page that will connect to a (Django) HTTP web service using XMLHttpRequest in the below script.
<script>
function UserAction() {
var req = createRequest(); // defined below
// Create the callback functions:
var handleResponse = function (status, response) {
alert("status " + status + " response: " + response)
}
var handleStateChange = function () {
switch (req.readyState) {
case 0 : // UNINITIALIZED
case 1 : // LOADING
case 2 : // LOADED
case 3 : // INTERACTIVE
break;
case 4 : // COMPLETED
alert("case 4" + req.responseType);
handleResponse(req.status, req.responseJson);
break;
default: alert("error");
}
}
req.onreadystatechange = handleStateChange;
req.open("GET", "https://foo.org:/bar/getid/?Id=" + document.getElementById('ID').value, true);
req.send();
function createRequest() {
var result = null;
if (window.XMLHttpRequest) {
// FireFox, Safari, etc.
result = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// MSIE
window.alert("windows");
result = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
// No known mechanism -- consider aborting the application
window.alert("no known mechanism");
}
return result;
}
}</script>
Using Chrome FireBase throws 404 error. Django server does not register any connection.
Using FireFox FireBase throws 404 error. But Django server throws
'code 400, message Bad HTTP/0.9 request type ('\x16\x03\x01\x00\xcc\x01\x00\x00\xc8\x03\x03\xdf\x04{\x9f\xe4\xb2\xc2ij\x8d\x14\xd5\xaa\xdcu\x14+&\xa4\xa1\xdf\xdc\xd8\x9b?\xea\xbdh\xb8')`
I did find this in the FireBase documentation here, making me think this is not possible. But hopefully I am wrong, or there is a way to do this in development/test, but not production.
SSL only: Firebase Hosting is SSL-only, meaning that content will only
be served over HTTPS. As you are developing your application make sure
that all external resources not hosted on Firebase Hosting are loaded
over SSL (HTTPS), including any external scripts. Most browsers do not
allow users to load "mixed content" (SSL and non-SSL traffic).
thanks

Related

AWS Load Balancer with HTTPS redirections for Server-side event (eventSource)

guys,
I am building a website with JAVA Spring on AWS Elastic beanstalk with Load Balancer. In short, I have a page which receives Server-side Event (SSE) from server using eventsource on client-side and SseEmitter on my Java Spring back-end.
I want my website to work with HTTPS so I followed official suggestion to set the NGINX configuration:
https://aws.amazon.com/premiumsupport/knowledge-center/redirect-http-https-elb/?nc1=f_ls
It works well...when I connect to my website with HTTP, it automatically redirect to HTTPS.
However, my server-side event stops working.
I tried solutions from another post:
EventSource / Server-Sent Events through Nginx
But it didn't help.
On my server side, I also add httpHeaders following other suggestions.
Server-side:
public static final class CustomSseEmitter extends SseEmitter {
static final MediaType UTF8_TEXT_EVENTSTREAM = new MediaType("text", "event-stream", Charset.forName("UTF-8"));
#Override
protected void extendResponse(ServerHttpResponse outputMessage) {
HttpHeaders headers = outputMessage.getHeaders();
headers.set("X-Accel-Buffering", "no");
headers.set("Cache-Control", "no-cache");
headers.set("Connection", "keep-alive");
headers.set("Content-Type", "text/event-stream");
if (headers.getContentType() == null) {
headers.setContentType(UTF8_TEXT_EVENTSTREAM);
}
}
}
Client-side:
var registerSSE = function (companyId, retryCount) {
source = new EventSource("/middle/registerSSE/" + companyId);
source.onopen = function (e) {
console.log("Build SSE successful");
};
source.onmessage = function (e) {
console.log("receive SSE");
};
source.onerror = function (e) {
console.error("SSE broken [" + e.data + "], retry " + (
++retryCount) + " times!");
}
}
Sorry I am kinda a newbie in this context, how can I combine both required features?
Any suggestions would be appreciated.
Thanks.

Angular 2 http get not working, never reaches the server

I am using a working project of Angular 2 from a Pluralsight course as a reference to make my first app.
This exisiting app fetchs the data from a Json file.
private _productUrl = 'api/products/products.json';
constructor(private _http: Http) { }
getProducts(): Observable<IProduct[]> {
return this._http.get(this._productUrl)
.map((response: Response) => <IProduct[]> response.json())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
If I modify the url to my own web service that runs locally "http://localhost:53785/api/Session" and run the angular 2 app, It never reaches the breakpoint that I set in my web service and I get "SyntaxError: Unexpected end of JSON input" error.
In the console I get:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error)"
Response
_body
:
""
headers
:
Headers
ok
:
false
status
:
500
statusText
:
"Internal Server Error"
type
:
2
url
:
"http://localhost:53785/api/Session"
proto
:
Body
Does anyone know why cant I reach my web service?
Thanks

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.

Google Apps Script and cookies

I am trying to Post and get a cookie. I am a newbie and this is a learning project for me. My impression is that if you use 'set-cookie' one should be able to see an additional 'set-cookie' in the .toSource. (I am trying to accomplish this on Google Apps Site if that makes a difference.) Am I missing something? Here is my code:
function setGetCookies() {
var payload = {'set-cookie' : 'test'};
var opt2 = {'headers':payload, "method":"post"};
UrlFetchApp.fetch("https://sites.google.com/a/example.com/blacksmith", opt2);
var response = UrlFetchApp.fetch("https://sites.google.com/a/example.com/blacksmith")
var openId = response.getAllHeaders().toSource();
Logger.log(openId)
var AllHeaders = response.getAllHeaders();
for (var prop in AllHeaders) {
if (prop.toLowerCase() == "set-cookie") {
// if there's only one cookie, convert it into an array:
var myArray = [];
if ( Array.isArray(AllHeaders[prop]) ) {
myArray=AllHeaders[prop];
} else {
myArray[0]=AllHeaders[prop];
}
// now process the cookies
myArray.forEach(function(cookie) {
Logger.log(cookie);
});
break;
}
}
}
Thanks in advance! I referenced this to develop the code: Cookie handling in Google Apps Script - How to send cookies in header?
Open to any advice.
When you aren't logged in Google Sites won't set any cookies in the response. UrlFetchApp doesn't pass along your Google cookies, so it will behave as if you are logged out.
First the cookie you want to send whose name is 'test' does not have a value. You should send 'test=somevalue'.
Second I am wondering if you are trying to send the cookie to the googlesite server and ask it to reply with the same cookie you previously sent... ?
I am thinking you are trying to act as a HTTP server beside you are a HTTP client.
As a HTTP client your role is only to send back any cookies that the HTTP server have previously sent to you (respecting the domain, expiration... params).

How to make multiple parallel web html requests in a Chrome Extension?

I'd like to retrieve and parse multiple html pages within a Chrome extension.
Using Web Workers for each request seemed like a simple way to make them execute in parallel. Is that possible? My attempt failed, perhaps because it's a known permissions bug.
As a workaround, I guess I could have the main extension page do multiple asynchronous XmlHttpRequests, then have the callback send the result page to Web Workers for parallel parsing. But that method raises the question of how many asynchronous parallel requests can Chrome make at once? That question has been asked here, without answer.
The Chrome Extension I'm writing is a Browser Action.
Code for the worker:
// Triggered by postMessage in the page
onmessage = function (evt) {
var message = evt.data;
postMessage(message.count + " started");
update(message.count, message.url);
};
// parse the results page
function parseResponse(count, url, resp) {
var msg = count.toString() + " received response ";
postMessage(msg);
}
// read the Buganizer URL and parse the result page
var update = function(count, url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
parseResponse(count, url, xhr.responseText);
}
}
xhr.onerror = function(error) {
var msg = "!>: " + count + ": error ";
postMessage(msg);
}
var url = "http://www.hotgrog.com"; // for testing (manifest has permissions for this url)
xhr.open("GET", url, true);
xhr.send();
postMessage(url);
}
Have you looked into trying asynchronous-loaders such as RequireJS or Curl?
Take a look at the authors explanation as to WHY we should use his product.