获取错误:解析 url 时出错:尝试使用 Sequelize 运行迁移时未定义

A. *_*Cam 3 javascript node.js express sequelize.js

我正在使用 Sequelize 作为我的 ORM 创建一个 Node.js/Express.js 应用程序。这是我正在遵循的教程。我在将表迁移到 Azure SQL 数据库时遇到问题。

我的config/config.json文件是这样的:

{
    "development" : {
       "use_env_variable" : "DATABASE_URL",
       "dialect" : "mssql"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的.env文件是这样的:

DATABASE_URL=<connection string here>

这些代码在以下代码中被调用models/index.js

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.json')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
Run Code Online (Sandbox Code Playgroud)

require('dotenv').config()在我的主要文件app.js。我的理解是该dotenv.env在整个项目中导出了我的所有变量。

当我尝试node_modules/.bin/sequelize db:migrate在终端中运行时,我得到

ERROR: Error parsing url: undefined

为什么它返回未定义?

这是我的文件结构,以防万一。

在此处输入图片说明

Abh*_*avD 6

你在哪里需要你的.env文件?运行迁移时,不需要此文件,因此会出现错误。

您应该添加require('dotenv').config();在你config/config.js为你的第一道防线。


小智 5

我希望这对某人有帮助,我通过使用以下命令在终端上导出 DATABASE_URL 解决了这个问题: export DATABASE_URL=postgresql://[user[:password]@][netlocation][:port][/dbname]

如此处所述: https: //tutel.me/c/programming/questions/45929489/use_env_variable+returned+undefined+in+sequelize