Serving your Angular CLI App Locally over HTTPS

综合技术 2018-03-14

When creating an Angular CLI app using the ng new command, the CLI itself will create some scripts in the packages.json relating to the building, testing, and local serving of your app.

When running npm start it will subsequently run ng serve which by default runs the web server on localhost in HTTP (e.g. http://localhost:4200 ). This is all well and good for local debugging of a standalone app, but if you need to run this inside an iframe on a site running HTTPS (like an Office Add-in or even a VSTS Extension), this becomes a challenge as your local app needs to be served over HTTPS as well.

Below is what you would see if you attempt to serve your content in HTTP when in an iframe of a document served over HTTPS:

Mixed Content: The page at ‘X’ was loaded over HTTPS, but requested an insecure resource ‘
http://localhost:4200/index.html&#8217 ; This request has been blocked; the content must be served over HTTPS.

Now you are more than able to run the Angular CLI web server in HTTPS through the –ssl , –ssl-cert , and –ssl-key switches, where you point to the location of a valid self-signed certificate/key for localhost. But, where do you get said certificates?

The easiest method I can find is to install browser-sync as a dev dependency.

npm install browser-sync –save-dev

This will install a self-signed certificate and key for localhost, which you can now point to when adding the –ssl switches mentioned above.

Change the start script in packages.json to the following

ng serve –ssl true –ssl-key /node_modules/browser-sync/lib/server/certs/server.key –ssl-cert /node_modules/browser-sync/lib/server/certs/server.crt

Now, when you call ng start NPM will run ng serve with the additional SSL switches, and serve your site under HTTPS (e.g. https://localhost:4200 ). From here on it should be smooth sailing.

Feature Photo by Joshua Sortino


AngularJS和Angular的路线图 看新闻很累?看技术新闻更累?试试 下载InfoQ手机客户端 ,每天上下班路上听新闻,有趣还有料! 在下一次主要版本发布后,AngularJS即将进入为期三年的LTS(长时间支持版本)。与此同时,Angular仍将保持每六个月发布一次主要版本。 根据NPM registry提供的...
Open links in a new window using AngularJS Is there a way to tell AngularJS that I want links to be opened in new windows when the user clicks on them? With jQuery I would do this: jQuery("...
Copy the next html content for brothers and sister... Whenever overlay element is clicked and startCopying() method is called, the text from copyTextTag should be copied in the pasteTextTag element. The...
Share Data Between Sibling Components In Angular U... Here, we will discuss how to share data between sibling components using Rxjs Behavior Subject in Angular 5 project with step by step demonstration...
Explaining Angular JS to You Like You’re Fiv... I came acrossthis post, which challenged me to wrap my head around the simplest way to explain the basic concepts of Angular. I used Angular ...