首页 > 解决方案 > 为托管在 Google App Engine 中的静态 React 应用重定向到 HTTPS

问题描述

我有一个托管在 GAE 灵活环境中的 nodejs 应用程序。我们已经设置了谷歌管理的 SSL,并且 https 路由有效。

但是由于我们静态地为应用程序提供服务,我们不能从服务器端强制重定向(据我所知)

这是服务器代码(我从 index.js 调用 start 方法):

const express = require('express')

const PORT = process.env.PORT || 8080

/**
 * Basic web server construction.
 * Parameter function passed into 'start' as serverProcess
 *    contains the actual meat of the server side processing
 *    for the node.js backend
 */
class WebServer {
  constructor () {
    this.app = express()
    this.app.use(express.static('dist/public'))
  }
  /**
   * Begins a web server executing the 'serverProcess' function provided
   * bodyParser.json() used as middleware to enable POST requests with JSON body content
   * @param {Function} serverProcess The business logic function for the node.js backend as a whole
   */
  start () {
    return new Promise((resolve, reject) => {
      try {
        this.server = this.app.listen(PORT, function () {
          console.log('Web server being created')
          resolve()
        })
      } catch (e) {
        console.error(e)
        reject(e)
      }
    })
  }
  stop () {
    return new Promise((resolve, reject) => {
      try {
        this.server.close(() => {
          resolve()
        })
      } catch (e) {
        console.error(e.message)
        reject(e)
      }
    })
  }
}

module.exports = WebServer

我该怎么做才能确保它始终重定向到 https?

我听说过 x-forwarded-proto,但我不确定它是什么以及如何实现它,而且由于它是一个灵活的环境,我不能使用 GAE 提供的处理程序。

标签: node.jsreactjsexpressgoogle-app-enginehttps

解决方案


所以我想出解决这个问题的方法是使用一个名为 express-https-redirect 的包,这是一个快速中间件,我只需使用 express.use('/', httpsRedirect()) 进行设置

我还取出了自己的组件类的路由并将它们设置在 index.js 文件中。

这就是我的 index.js 文件现在的样子(以前是 web.server.js 是从 index.js 开始的)

'use strict'
require('dotenv').config()
const consts = require('./consts/consts')
const httpsRedirect = require('express-https-redirect')

console.log(consts.database)

const express = require('express')
const PORT = process.env.PORT || 8080

const app = express()

app.use('/', httpsRedirect())
app.use(express.static('dist/public'))

app.listen(PORT, function () {
  console.log('Web server was started at ', PORT)
})

推荐阅读