node.js - 为托管在 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 提供的处理程序。
解决方案
所以我想出解决这个问题的方法是使用一个名为 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)
})
推荐阅读
- java - 在同一浏览器 Selenium (JAVA) 中同时打开多个 URL
- javascript - 如何使用javascript查找块并替换长字符串
- asp.net-mvc - 如何在不使用配置转换的情况下将 Azure webapp 部署到多个环境
- ios - iOS 11:是否可以不显示通知警报(作为横幅),但应该在通知中心添加?
- c# - 不可调用成员 'xyz' 不能像方法一样使用,vb 和 c# 之间的区别
- mysql - 如何解决错误:ERROR 1442 (HY000) Can't update table 'table name' in stored function/trigger?
- redhat - 创建邮箱文件:文件存在
- android - 添加到库后如何在 Android Studio 中使用 JSONLibrary
- python - 仓库库存需求管理
- docker - docker compose vs docker start