【问题标题】:Redirecting to HTTPS for a static React app hosted in Google App Engine为托管在 Google App Engine 中的静态 React 应用重定向到 HTTPS
【发布时间】:2018-08-10 18:35:57
【问题描述】:

我有一个在 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.js reactjs express google-app-engine https


    【解决方案1】:

    所以我想出解决这个问题的方法是使用一个名为 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)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多