【发布时间】:2019-06-24 11:21:19
【问题描述】:
默认情况下,如果我们运行 Angular 应用程序,它们会以 http 运行(例如在 http://localhost:4200 上)。
如何将其从http 转换为使用https?
【问题讨论】:
-
但是,那是针对 angularjs 的,他想使用 $http(specific) 使其成为 https
默认情况下,如果我们运行 Angular 应用程序,它们会以 http 运行(例如在 http://localhost:4200 上)。
如何将其从http 转换为使用https?
【问题讨论】:
简单修复而不是运行:
ng s -o
使用额外的属性运行它:
ng s -o ---ssl true
它将在https://localhost:4200 上运行。但是,如果您有一个 .crt 和一个 .key 文件,那么也添加该属性。
您会看到一个以 https 开头的浏览器,尽管它会显示“不安全”作为警告。
如果您只想在 https 上运行并且不关心“不安全”消息,这就足够了。如果您确实关心,请继续执行进一步的说明。
ng s -o ---ssl true --ssl-key <path to key file> --ssl-cert <path to crt file>
或给出.key 和.crt 文件的相对路径。
如果您不想每次都提供这些属性,或者不想为 Angular 运行完整的 NGINX 服务器,那么根据 Angular 版本将这些属性添加到 angular.json 或 angular-cli.json :
"serve":
{
"builder": "@angular-devkit/build-angular:dev-server",
"options":
{
"browserTarget": "ideationapp:build",
"ssl": true,
"sslKey": "ssl/server.key",
"sslCert": "ssl/server.crt",
}
}
如果您没有.key 和.crt 文件,则不需要sslkey 和sslcert。
在这里,我假设这两个文件都在 ssl 目录中,其中 src.现在,只运行ng s -o 就足以通过angular.json 文件使用证书。
如何仅为您的计算机或仅为一个用户创建 localhost 的临时修复。
要求:
现在转到 Git bash 并一次输入此命令
git clone https://github.com/RubenVermeulen/generate-trusted-ssl-certificate.git(cloned to local computer)
cd generate-trusted-ssl-certificate(Going to application path)
bash generate.sh(starting shell script wher we called openssl)
克隆的应用程序使用 openssl(用于保护计算机网络通信免受窃听或需要识别另一端方的应用程序的软件库)生成 .crt 和 .key 文件
它将创建server.key 和server.crt 文件。
现在点击 server.crt
对于 OS X
Windows 10
证书现已安装。
现在将证书存储在ssl 目录中。
现在使用命令行来提供 ssl 密钥和证书,或者将这些文件添加到 angular.json(或 angular-cli.json,取决于您的 Angular 版本)。
您不会看到任何“不安全”,如果您单击地址栏旁边的锁定图标,它将显示“安全”。
但是,如果您将在他人的笔记本电脑上运行该应用程序,它会显示“不安全” 因为他们没有安装证书(受信任)。
【讨论】:
要在 https 上运行 Angular 应用程序,请执行以下步骤。 npm install -g angular-http-server
Cd 站点路径和 dist 文件夹 (ClientApp/dist)
Angular-http-server -o
默认运行在 8080 端口并使用 http
使用 -p 指定端口,例如Angular-http-server -p 44367 -o
要启用 https,您必须使用 --key 和 --cert 标志手动指定自签名证书的路径
angular-http-server --https --key c:/localhost.key --cert c:/localhost.crt -p 44367 -o 要么 angular-http-server --https --key “密钥存储的路径” --cert“路径”
如果本地计算机上未安装 ssl,此时您可能会看到一些错误。
如果机器上没有安装 OpenSSL,请从以下链接下载
http://slproweb.com/download/Win64OpenSSL-1_1_0L.exe
生成 OpenSSL 的命令
openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout localhost.key -days 3560 -out localhost.crt -config certificate.cnf
下面的链接描述了如何创建证书,配置 CLI 使用
https 和信任 Windows 上的证书。
https://medium.com/@richardr39/using-angular-cli-to-serve-over-https-locally-70dab07417c8
【讨论】:
不需要花哨的东西,只需将标志 --https 添加到您的启动脚本中即可。
例如:
"scripts": {
"start": "webpack-dev-server --content-base src/ --progress --inline --hot --https"
}
【讨论】: