Force angular js app on heroku to use http instead of https? - angularjs

I am querying an "http" API with my app, so every time I access my application on heroku (which is https enabled by default), CORS complains about cross-origin domain requests.
Asking the owner of the API to make it "https" is not an option, so I was wondering if it was possible to force my application to always use http? This is a node.js built application. (More specifically, it is a yeoman-generated angular js app). In Rails, I've seen several posts on Stack OverFlow saying this can be easily done with something like config.force_ssl = false, so I was wondering whether something similar could work for a node.js application (either something in the code or on Heroku specifically).

As a fix, I wrote an AngularJS Factory that routes all https requests to http:
.factory('DisableSSL', function($location, $window){
return {
activate: function() {
if ($location.protocol() !== 'http') {
$window.location.href = $location.absUrl().replace('https', 'http');
}
}
};
})
This factory is included in all of my other controllers and the activate function is called.
Note that this doesn't work if you're using a browser extension like HTTPSEverywhere.

Related

$http.get returns index.html using Ionic v1 and Firebase hosting

We currently have a Ionic v1 project that calls an API implemented as a Google App Engine application. This Ionic app runs with Ionic serve, PhoneGap, and when deployed to Android/iOS.
We are now trying to deploy to the web using Firebase hosting.
The initial HTML/JS code all runs correctly until we reach an $http.get call to the Google App Engine. What happens then is that the request reaches the GAE server and is processed correctly there with a response being sent back. But in the client code, the response.data property is the contents of the Firebase application’s index.html rather than the response that was supplied from GAE.
We don’t know why this is happening, or how to fix it, but here are some relevant facts:
When we run the app on a device using PhoneGap or via the Google Playstore, the URL by which we access GAE is the same URL if we were accessing GAE from a browser. But, when we run the app via “ionic serve” we must use a proxy to work around a CORS issue. What we do is to specify a simplified URL in the Ionic code, and then provide a mapping of that simplified URL to the GAE’s actual URL in a file called “ionic.project” which looks something like this:
{
"name": "proxy-example",
"app_id": "",
"proxies": [
{
"path": "/api",
"proxyUrl": "http://cors.api.com/api"
}
]
}
When we attempt to deploy the app via either “firebase deploy” or “firebase serve” we must use the proxy version of the URL in our $http.get call. Otherwise the call does not reach the GAE server at all. It is not clear how Firebase knows to use “ionic.project” for the proxy mapping.
We are not using “Angularfire”, only the standard AngularJS library that is packaged with Ionic 1.x
Thanks for any help you can offer.

Redirect from http to https on localhost with create-react-app to test with Lighthouse

I have configured create-react-app to use https in my local development environment. I would now like to convert my React application to a progressive web app and I plan to use Lighthouse to check my status. I am running Lighthouse as a Chrome plugin, but I am having trouble with the part when it is checking if my HTTP requests are redirected to HTTPS. They are not.
I have been crawling through my node_modules and I have taken a look at webpack-dev-server that is bundled with create-react-app. I have tried to make some changes, but the best I have managed so far is that I have gotten "Too many redirects".
TL;DR: How can I configure create-react-app to redirect all requests from http to https on my local dev environment?
Here's the code from my create-react-app if you are having trouble with just the redirect part. I'm doing it manually since Heroku doesn't automatically handle it. But this actually needs to be handled on the server because it makes the app visibly load twice if it has to redirect to http. But for now, I'm redirecting in the constructor of my App component.
constructor(props, context) {
const url = window.location.origin
if (!url.includes('localhost') && !url.includes('https')) {
window.location = `https:${url.split(':'))[1]}`
}
}
For your purposes, you'd just need to take out the localhost part and make the new url a little differently (because of the port).
I'm using ramda here, but lodash also has a tail function you can use.
import { tail } from 'ramda
...
constructor(props, context) {
const url = window.location.origin
if (!url.includes('https')) {
window.location = `https:${tail(url.split(':')).join(':')}`
}
}
#Fmacs, for redirection of HTTP traffic to HTTPS, instead of using local dev-server, deploy your app on any environment like Heroku or Firebase. Firebase is very simple. I see that you also have other issues running the create-react-app that you created. I have explained how to do this in simple steps in a blog post with sample code in GitHub. Please refer to: http://softwaredevelopercentral.blogspot.com/2019/10/react-pwa-tutorial.html

On Ionic 2, XMLHttpRequest cannot load .. with Laravel api

This is my scenario:
XMLHttpRequest cannot load http://phi.dev/api/login. Redirect from 'http://phi.dev/api/login' to 'http://localhost:8100/' has been blocked by CORS policy: Request requires preflight, which is disallowed to follow cross-origin redirect.
I have a Aungular2/Ionic 2 App on local and a Laravel Web API for authenticating user.
if I call this Web API from my Angular2 Module, I get an exception as given above.
Note: In Chrome Network, I could my angular service is being called 2 times. First with Request Method: OPTIONS and second time with Request Method: Get, which returns Http 302.
Does anyone know how to resolve this issue.
Thanks in advance.
Because the request is external and because you are serving the application locally you will have CORS issues.
To avoid such issues locally (when using ionic serve), you have to setup a local proxy in the ionic configuration files.
Check your Ionic 2 project directory and locate the file ionic.config.json: it usually is in the root directory of the project (and need to be there, along with package.json and so on).
Open the file, and add this (do not forget to be SURE that the line BEFORE that one ends with a comma (,), since it's a json file):
"proxies": [
{
"path": "/server",
"proxyUrl": "http://phi.dev"
}
]
Now, in the section where are you are performing the HTTP request, replace the http://phi.dev with /server. I will give you an example here.
I do recommend you, however, to be aware that such edit will make your compiled app to NOT work, so you likely want to put a debug flag for testing and compiled environments, like this:
class MyServiceOrComponent {
private debug: boolean = true; // Set this flag to FALSE when you need to actually compile the app for any real device.
private server: string = this.debug ? "/server" : "http://phi.dev";
constructor(private http: HTTP) {
const login = "/api/login"; // don't to it exactly like that, make a static list or something like this to store paths.
let request = this.http.get(this.server + login).then((res) => {
console.log(res);
});
}
}
What happens, explained briefly, is that if you perform the HTTP request as "localhost" it will throw you an exception (because of the CORS policy). Such will happen only when you are running the application in your testing environment (localhost). To avoid such, you provide a proxy, so that the request will be valid.

Is it possible to build a hybrid app with Angular?

I build an AngularJS application that I expected to work as a hybrid application for mobile devices. As such the application would run locally from the file system.
When the $routeProvider gets the html file I get the following message.
This is a CORS violation obviously but the file is local and trying to access another local file. It's not like a web site is trying to access a clients local files. This is the client.
I can't spin up a web server to serve up the local files because this will be packaged up and deployed as a local application.
I know people build hybrid mobile applications all the time. What I can't figure out is how they do this with AngularJS and why AngularJS doesn't either offer a solution or prescribe how to get around CORS.
I'm open to all suggestions. Thanks all.
XMLHttpRequest cannot load file:///D:/SubversionRits/SourceCode/Verso%20-%20Mashup%20Proposal/MarshupSource/MashupCoreUI/core/apps/mashup/welcome/welcome.html. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource. VM36 angular.js:8380
Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/SubversionRits/SourceCode/Verso%20-%20Mashup%20Proposal/MarshupSource/MashupCoreUI/core/apps/mashup/welcome/welcome.html'.
Here is my route config
mashupApp.config(function ($routeProvider, $httpProvider) {
// I've tried all these with no effect.
//$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
//$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//$routeProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
//$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//$httpProvider.defaults.useXDomain = true;
//delete $httpProvider.defaults.headers.common['X-Requested-With'];
$routeProvider
.when('/about', {
templateUrl: 'apps/mashup/about/about.html',
controller: 'aboutController',
resolve: {
loadMyCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
// you can lazy load files for an existing module
return $ocLazyLoad.load({
name: 'mashupApp',
files: ['apps/mashup/about/aboutController.js', 'apps/mashup/~appServices/dataService.js']
});
}]
, sessionLoad: function ($route, sessionLoad) { return sessionLoad.loadCompleted(); }
}
})
.when('/', {
templateUrl: 'apps/mashup/welcome/welcome.html',
sessionLoad: function ($route, sessionLoad) { return sessionLoad.loadCompleted(); }
}
})
;
});
I don't know the details, but I'm pretty sure HabitRPG's Android app uses Angular.
https://github.com/HabitRPG/habitrpg-mobile
Ok, I figured it out.
Running a web app from a file doesn't work because of CORS but when you are packaged up in Phonegap or Cordova inside the Intel XDK everything works.
I took my application and created a blank Intel XDK project and copied my web files to it without changing anything.
It all worked!
Thanks for those who offered ideas and suggestions. I really appreciate it.
I see how this can work now.
If you want to create a hybrid mobile app with AngularJS, you should definitely checkout the Ionic Framework.
From the Ionic website:
A match made in heaven. Ionic utilizes AngularJS in order to create a framework most suited to develop rich and robust applications. Ionic not only looks nice, but its core architecture is for serious app development, and AngularJS ties in perfectly.
You can't access the files directly due to browser security settings, but you can store data etc in localstorage and use that when the app is offline.
Someone has put together an example here http://amitavroy.com/justread/content/articles/html5-local-storage-angular-js

Phonegap angularjs $http.post() always returns http code 200

Angularjs v. 1.2.0rc3 with phonegap 3.1 and django-rest-framework
When posting data to my API (login form) I am getting status 200 in angularjs no matter if I authenticate with proper credentials etc. Even though I simply return HTTP_400 in the API view as in the example below, angularjs thinks this is a HTTP_200 status code.
I am sure the backend API returns HTTP_400 which works fine when using local http server.
I can also confirm this by debugging the api view.
Here's the example code.
Django Rest Framework code:
class LoginView(APIView):
def post(self, request):
return Response({}, status=status.HTTP_400_BAD_REQUEST)
and my angularjs controller:
$scope.login = function () {
$http.post(API_URL, $scope.loginUser).then(
function(response) {
console.log('STATUS : ' + response.status);
console.log('request OK');
},
function() {
console.log('request is NOT OK');
)};
As far as I know phonegap uses a local file:// protocol so there should be no CORS
related problem ?
When the same on chrome browser, I get Origin file:// is not allowed by Access-Control-Allow-Origin. Adding --disable-web-security flag to chrome startup script eliminates this problem but it does not solve the "always 200 status code" for phonegap.
Testing on android 2.3 & phonegap 3.1 & angularjs 1.2.0rc3
Confirmed fixed in AngularJS 1.2.3
See the line here:
https://github.com/angular/angular.js/blob/v1.2.3/src/ng/httpBackend.js#L122
Upgrade to Latest(version 1.2.9) AngularJS version, Its resolved now.

Resources