我有一个工作没有错误的后端,所以我试图将它发送到Heroku服务器,因为这是我第一次尝试使用Heroku,我选择了一个免费的数据库(JawsDB MySQL),但试图将我的本地数据库MySQL更改为Heroku上我的。env文件不再工作,我已经尝试改变了几件事,但我总是有一个错误与我的。env文件
.env:6
DB_HOST=qao3ibsa7hhgecbv.cbetxkdyhwsb.us-east-1.rds.amazonaws.com,
在MySQL工作台上安装我的数据库,我没有得到错误,但我找不到一种方法来设置它在我的。env文件这是我的。env文件:
require('dotenv').config();
module.expots = {
authSecret: 'myauthsecret',
db: {
DB_HOST=dbhost.us-east-1.rds.amazonaws.com,
DB_USER=dbuser,
DB_PASSWORD=dbpassword
DB_PORT=3306,
DB_DATABASE=dbname
}
}
My auth secret被passport.js使用
这里是我的knexfile.js,我设置我的数据库凭据:
const { db } = require('./.env');
module.exports = {
client: 'mysql2',
connection: {db,
mysqlhost: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
};
我不知道这有什么问题,在我的本地机器上,我曾经这样设置我的。env:
module.exports = {
authSecret: 'sqt;n/eP-kX-(J#I#8WahB|uhx/i)^$aZ[ZD!PADRZ#Qn@^s;Sl]~wI?3ADxF',
db: {
host: '127.0.0.1',
port: '3306',
user: 'root',
password : 'aPassword',
database : 'database'
}
}
它正在工作,现在我不知道我应该做什么使它与我的数据库在Heroku工作…
你得到的错误是因为你正在加载.env
作为JS代码和db
对象不是有效的JS。它应该像这样有效JS:
module.expots = {
authSecret: 'myauthsecret',
db: {
DB_HOST: "dbhost.us-east-1.rds.amazonaws.com",
DB_USER: "dbuser",
DB_PASSWORD: "dbpassword",
DB_PORT: 3306,
DB_DATABASE: "dbname",
}
}
也就是说,对.env
文件应该有什么以及如何使用它存在误解。正确的.env
含量应该是:
# .env
# Replace with the correct values
DB_HOST=dbhost.us-east-1.rds.amazonaws.com
DB_USER=dbuser
DB_PASSWORD=dbpassword
DB_PORT=3306
DB_DATABASE=dbname
然后在你的knexfile.js
中你做:
// This loads the .env variables into the process.env
require('dotenv').config();
module.exports = {
client: 'mysql2',
connection: {
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
database: process.env.DB_DATABASE
},
...
};
server.js
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import routes, { notFoundRoute } from './routes';
import errorHandler from './errorHandler';
const port = process.env.PORT || 4000;
const app = express();
const config = () => {
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json());
app.use(cors());
};
const serve = async () => {
app.use('/api/v2/', routes());
app.use(notFoundRoute);
app.use(errorHandler);
app.listen(port, () => {
// eslint-disable-next-line no-console
console.log(`Server is up on port ${port}`);
});
};
const init = async () => {
config();
await serve();
};
init();
Package.json
{...
"type": "module",
"main": "server.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "nodemon --experimental-modules --es-module-specifier-
resolution=node -r dotenv/config server.js"},