[Rails] Webpacker的HTTPS设置

Rails 6.0后 Webpacker已经取代 Asset Pipeline 成为初步的前端打包方案,安装方法Webpacker Github上的README有很详尽的说明「Installation」。

上一篇文章中,介绍了如何在 Rails development 环境中使用 HTTPS 连线至 localhost server,并启用 HSTS。

此时用预设的 config/webpacker.yml 下去启用 webpack-dev-server,其编译后的 JavaScript 依然以 HTTP 提供。
但 Rails server 的 HSTS 设定会把
http://localhost:3000/packs/js/application-2be7c5d587f23021bfe9.js
转换成请求
https://localhost:3000/packs/js/application-2be7c5d587f23021bfe9.js
这下就发生找不到资源的错误了:

GET https://localhost:3000/packs/js/application-2be7c5d587f23021bfe9.js net::ERR_ABORTED 500 (Internal Server Error)
localhost/:10
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
application-2be7c5d587f23021bfe9.js:1
Rack app error handling request { GET /packs/js/application-47a01f2c35f03c5131aa.js }
#<EOFError: end of file reached># ORPuma caught this error: end of file reached (EOFError)
# OR
GET https://localhost:3035/sockjs-node/info?t=1570436376957 net::ERR_SSL_PROTOCOL_ERROR
sockjs.js:1796
Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR
:3035/sockjs-node/info?t=1570436373828:1

webpack-dev-server

启用 HTTPS

修改 config/webpacker.yml 将 development.dev_server.https 设为 true

重启 rails server 与 ./bin/webpacker-dev-server 后,还是错的!

#HTTPS凭证错误

Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID
:3035/sockjs-node/info?t=1570452520941:1
GET https://localhost:3035/sockjs-node/info?t=1570452524158 net::ERR_CERT_AUTHORITY_INVALID

指定凭证

webpack-dev-server 指定凭证的方式可以看「DevServer

Rails开发环境中启用HTTPS中我们将 mkcert 自签的凭证放在 config/ssl/ 下,于是我们必须修改 config/webpacker.yml 指定 development.dev_server.https.cert 与 development.dev_server.https.key 使用凭证,如下:

你以为成功了吗?重启 rails server 与 ./bin/webpacker-dev-server 后,还是错的!原因在于 4.0.7 版的 Webpacker 忽略了我们传入的 https 参数,只 care 是否为 true。

直到这个 PR 才修正了这个错误。「coerce https yaml config to boolean #2251

因此,我们至少需要指定 Gem Webpacker 版本号到 commit d577bab 以后,直到 4.0.8 版释出:

# Gemfile
gem "webpacker", git: 'https://github.com/rails/webpacker.git', ref: 'd577bab'

bundle 安装更新套件,重启 rails server 与 ./bin/webpacker-dev-server 后,就能成功啰!

但如果你的 Content Security Policy 像我一样设定错误,忘了加上 https:// 与 wss:// 的话,我只能说:「革命尚未成功,同志仍需努力。」

# Content Security Policy 設定錯誤
Refused to connect to 'wss://localhost:3035/sockjs-node/661/ghika1m3/websocket' because it violates the following Content Security Policy directive: "connect-src 'self' https: http://localhost:3035 ws://localhost:3035".
sockjs.js:1887

设定 Content Security Policy

到 config/initializers/content_security_policy.rb 下添加https://localhost:3035 与 wss://localhost:3035 到 policy.connect_src 中:

这下总算是成功在 development 环境下全面启用 SSL 啰!有人问我说为何我不直接把成功的设定分享给读者,要带着读者一起错过来,原因有三:

  1. 这样读者能够理解是哪个部分导致错误
  2. 把常遇到的相关错误记录下来,方便同踩此坑的兄弟们 Google
  3. 我花了 6 个小时 debug,你们直接过,我心里不平衡啦

转载需保留链接来源:软件玩家 » [Rails] Webpacker的HTTPS设置

赞 (2)