在我的next.js应用程序中,我尝试将prescription之后的env
对象暴露在我的next.config.js
中;
//next.config.js
const withCSS = require('@zeit/next-css');
module.exports = withCSS({
webpack(config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
});
return config;
}
});
//trying to expose the env {} below
module.exports = {
env: {
DEVELOPMENT_DB_DSN: 'mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority',
PRODUCTION_DB_DSN: 'mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority',
TEST_DB_DSN: 'mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority'
}
};
我也尝试过:
var withCSS = require('@zeit/next-css');
module.exports = {
withCSS: withCSS({
webpack(config) {
config.module.rules.push({
test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]'
}
}
});
return config;
}
}),
env: {
DEVELOPMENT_DB_DSN: `mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority`,
PRODUCTION_DB_DSN: `mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority`,
TEST_DB_DSN: `mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority`
}
};
我正在尝试在这里使用它们:
var express = require('express')
var next = require('next')
var session = require('express-session')
var MongoStore = require('connect-mongo')(session)
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var cors = require('cors')
var morgan = require('morgan')
var HttpStatus = require('http-status-codes')
var PORT = process.env.PORT || 8016
var dev = process.env.NODE_ENV !== `production`;
function processNODEENVCheckerAndServerRuntimeConfigSetter(ENV) {
var environment,
environments = {
'production': () => {
environment = process.env.PRODUCTION_DB_DSN; //trying to use them here
return environment;
},
'test': () => {
environment = process.env.TEST_DB_DSN; //trying to use them here
return environment;
},
'default': () => {
environment = process.env.DEVELOPMENT_DB_DSN; //trying to use them here
console.log("environment ", environment);
return environment;
},
};
(environments[ENV] || environments['default'])();
return environment
}
var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV)
var NextApp = next({ dev })
var handle = NextApp.getRequestHandler()
var mongoose = require('mongoose')
NextApp.prepare()
.then(() => {
const app = express()
mongoose.connect(db, { useNewUrlParser: true })
mongoose.Promise = global.Promise
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${db}`)
})
.on('error', err => {
console.log(`Connection error: ${err.message}`)
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(morgan('dev'))
app.use(cookieParser())
session({
secret: 'very secret 12345',
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
app.use(cors())
app.use('/auth', require('./auth'))
app.get('*', (req, res) => {
return handle(req, res)
})
app.use(errorHandler, function (error, req, res, next) {
res.json({ message: error.message })
})
app.listen(PORT, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${PORT}`)
})
})
.catch(err => {
console.error(err)
})
最后,应用程序坏了,我得到了这个错误...
environment undefined
Compiled successfully!
Note that pages will be compiled when you first load them.
{ MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at new MongooseError (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at NativeConnection.Connection.openUri (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/connection.js:519:11)
at Mongoose.connect (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/node_modules/mongoose/lib/index.js:314:15)
at NextApp.prepare.then (/Users/antoniopavicevac-ortiz/Dropbox/developer_folder/hillfinder/server/index.js:68:14)
at process._tickCallback (internal/process/next_tick.js:68:7)
message:
'The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.',
name: 'MongooseError' }
[nodemon] clean exit - waiting for changes before restart
不确定在undefined
语句/函数中为什么从console.log("environment ", environment);
得到var db = processNODEENVCheckerAndServerRuntimeConfigSetter(process.env.NODE_ENV)
答案 0 :(得分:0)
在 next.config.js 中使用env
选项只会在构建时使环境变量可用。
要使环境变量可用于服务器,可以将环境变量放在项目根目录下的.env
文件中:
DEVELOPMENT_DB_DSN="mongodb+srv://antonioHillfinder:foo@hillfinder-qjxuo.azure.mongodb.net/development?retryWrites=true&w=majority"
PRODUCTION_DB_DSN="mongodb+srv://antonioHillfinder:bar@hillfinder-qjxuo.azure.mongodb.net/production?retryWrites=true&w=majority"
TEST_DB_DSN="mongodb+srv://antonioHillfinder:foobar@hillfinder-qjxuo.azure.mongodb.net/test?retryWrites=true&w=majority"
然后,您可以使用 dotenv 软件包进行加载:
https://www.npmjs.com/package/dotenv
npm i dotenv
...并将其添加到服务器文件的顶部:
require('dotenv').config()
此后,您的环境变量将在您的服务器上可用。
请注意, next.config.js 中的env
选项用于在构建期间使环境变量可用,并且可以这样使用:
// next.config.js
const withCSS = require('@zeit/next-css');
module.exports = withCSS({
webpack(config) {
// ...
return config;
},
env: {
// ...
}
});