如何解决"Middleware " strapi::session ": App keys are required" 错误,将 Strapi 部署到 Heroku?



我按照官方说明将我的strapi入门应用程序部署到Heroku。该应用程序在本地运行良好。我在部署说明中唯一遗漏的是安装PG节点模块(它已经安装了,因为我的本地应用程序使用Postgresql(。

访问Heroku日志,我看到这个:

error: Middleware "strapi::session": App keys are required. 
Please set app.keys in config/server.js (ex: keys: ['myKeyA', 'myKeyB'])

也许这是一个重要的细节:我遵循了这个过程一次,一切都成功了。我能够部署到赫罗库。我再试了一次,但没有成功。我想Heroku可能对我重新使用应用程序名称有问题,但我试图在Heroku中为应用程序命名不同的名称,但我仍然遇到了同样的错误。

heroku是否在错误的位置查找我的server.js文件?它应该在我的"/config/env/production";文件夹而不是我的"/config";文件夹

按照指示,这是我的/config/env/production/database.js

const parse = require('pg-connection-string').parse;
const config = parse(process.env.DATABASE_URL);
module.exports = ({ env }) => ({
connection: {
client: 'postgres',
connection: {
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false
},
},
debug: false,
},
});

这是我的/config/env/production/server.js

module.exports = ({ env }) => ({
url: env('MY_HEROKU_URL'),
});

这是我的/config/server.js

module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
app: {
keys: env.array('APP_KEYS'),
},
});

我的包.json很好的衡量标准:

{
"dependencies": {
"@strapi/plugin-graphql": "^4.0.0",
"@strapi/plugin-i18n": "4.0.6",
"@strapi/plugin-users-permissions": "4.0.6",
"@strapi/strapi": "4.0.6",
"lodash.set": "^4.3.2",
"pg": "8.6.0",
"pg-connection-string": "^2.5.0"
},
"name": "backend",
"private": true,
"version": "0.1.0",
"description": "A Strapi application",
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi"
},
"devDependencies": {},
"author": {
"name": "A Strapi developer"
},
"strapi": {
"uuid": "f64b509e-2d95-4464-8d39-d6f0d1c7a31a",
"template": "@strapi/template-corporate@^1.0.0",
"starter": "@strapi/starter-next-corporate"
},
"engines": {
"node": ">=12.x.x <=16.x.x",
"npm": ">=6.0.0"
},
"license": "MIT"
}

我正在运行Node v14.18.3和NPM v6.14.15

我在./config/env/production/server.js中解决了这个问题

module.exports = ({ env }) => ({
url: env("MY_HEROKU_URL"),
proxy: true,
app: {
keys: env.array("APP_KEYS", ["testKey1", "testKey2"]),
},
});

testKey1、testKey2只是占位符,需要通过heroku 中的CONFIG VAR用2个随机密钥替换

APP_KEYS=someSecret,anotherSecret

CCD_ 2也很重要。否则会抛出Cannot send secure cookie over unencrypted connection

只需在项目的根目录中创建.env文件,如下所示:

HOST=0.0.0.0
PORT=1337
APP_KEYS=jP8pb1lYsAhnmURarewxhA==,34xnLMYHY5jiU7ONTstTqQ==

如@Temo所述,将环境变量添加到文件中不是正确的解决方案。尽管它有效,但它也带来了相当多的安全威胁。

您应该做的是将APP_KEYS添加到Heroku上的环境变量中。您可以通过使用以下代码创建一个文件来生成一个新密钥:

// filename: generateCode.js
const crypto = require('crypto')
console.log(crypto.randomBytes(16).toString('base64'))

然后用从控制台运行

node generateCode.js

它生成的代码看起来有点像foP7OJcuRhCw1sTR6EfZPw==。将其用作您在Heroku中的APP_KEY。

在Heroku上,对于特定的应用程序,导航到设置->配置vars并在其中添加环境变量。

所以您只需要在Heroku设置中创建一个变量->config变量称为APP_KEYS。这个变量的值可以从.env文件中获得,其中应该有值为的APP_KEYS变量。

只需从git-ignore中删除.env。然后再推一次。

相关内容

最新更新