Так что только что развернуло мое приложение Next. js в Heroku. И я смог сделать запросы к базе данных разработки и получить доступ ко всем маршрутам / конечным точкам отлично, кажется, что он может только успешно сделать один запрос в производстве users/login
.
На Heroku я установил следующий Config Vars
DATABASE_NAME production
MONGODB_URI mongodb+srv://antonio:xxxxx@hillfinder-qjxuo.mongodb.net/production?retryWrites=true
NODE_ENV production
NODE_MODULES_CACHE false
NPM_CONFIG_PRODUCTION true
И этот файл server/index.js
:
const express = require('express');
require('dotenv').config();
const nextJS = require('next');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var bodyParser = require('body-parser');
var auth = require('./lib/auth');
var cors = require('cors');
var morgan = require('morgan');
var HttpStatus = require('http-status-codes');
var compression = require('compression');
var helmet = require('helmet');
const MongoClient = require('mongodb').MongoClient;
var PORT = process.env.PORT || 8016;
const { isBlockedPage, isInternalUrl } = require('next-server/dist/server/utils');
function NODE_ENVSetter(ENV) {
var environment,
environments = {
production: () => {
environment = process.env.PRODUCTION_DB_DSN;
console.log(`We are currently in the production environment: ${environment}`);
return environment;
},
test: () => {
environment = process.env.TEST_DB_DSN;
console.log(`We are currently in the test environment: ${environment}`);
return environment;
},
default: () => {
environment = process.env.DEVELOPMENT_DB_DSN;
console.log(`We are currently in the development environment: ${environment}`);
return environment;
}
};
(environments[ENV] || environments['default'])();
return environment;
}
// var db = NODE_ENVSetter('production');
// var db = process.env.MONGODB_URI;
var mongoose = require('mongoose');
// const config = require('./config/mongo');
var env = process.env.NODE_ENV || 'development';
function errorHandler(err, req, res, next) {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Log error
console.error(err.stack);
// Render the error page
res.status(err.status || 500);
// Default error message by HTTP code
res.render('error', {
title: HttpStatus.getStatusText(err.status),
message: HttpStatus.getStatusText(err.status)
});
}
async function start() {
const env = process.env.NODE_ENV == 'production';
const app = nextJS({ env });
const server = express();
await app
.prepare()
.then(() => {
const client = new MongoClient(process.env.MONGODB_URI, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db('production').collection('devices');
// perform actions on the collection object
client.close();
});
// mongoose.connect(process.env.MONGODB_URI, {
// 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}`);
// });
})
.catch(err => {
console.error(err);
});
server.set('view engine', 'html');
server.use('/uploads', express.static(__dirname + '/uploads'));
server.use(
bodyParser.urlencoded({
limit: '50mb',
extended: false
})
);
server.use(morgan('dev'));
server.use(cookieParser());
server.use(
session({
secret: 'very secret 12345',
resave: false,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
})
);
server.use(compression());
server.use(helmet());
server.use(auth.initialize);
//Compress all routes
server.use(auth.session);
server.use(cors());
server.use('/users', require('./users'));
server.use('/images', require('./images'));
// Redirect all requests to main entrypoint pages/index.js
server.get('/*', async (req, res, next) => {
try {
const pathName = req.originalUrl;
if (isInternalUrl(req.url)) {
return app.handleRequest(req, res, req.originalUrl);
}
if (isBlockedPage(pathName)) {
return app.render404(req, res, req.originalUrl);
}
req.locals = {};
req.locals.context = {};
const html = await app.renderToHTML(req, res, '/', {});
// Handle client redirects
const context = req.locals.context;
if (context.url) {
return res.redirect(context.url);
}
// Handle client response statuses
if (context.status) {
return res.status(context.status).send();
}
// Request was ended by the user
if (html === null) {
return;
}
app.sendHTML(req, res, html);
} catch (e) {
next(e);
}
});
// catch 404 and forward to error handler
server.use(function(req, res, next) {
next(createError(404));
});
// error handler
server.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.errorStatus = err.status;
res.locals.errorMessage = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
console.log('err.status ', err.status);
res.status(401).send(err.message);
});
if (process.env.NODE_ENV === 'production') {
server.use(express.static('build'));
// Add production middleware such as redirecting to https
// Express will serve up production assets i.e. main.js
// If Express doesn't recognize route serve index.html
const path = require('path');
server.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(PORT, err => {
if (err) throw err;
console.log(
`> Ready and listening on PORT:${PORT} in the ${process.env.NODE_ENV} environment`
);
});
} else {
server.listen(PORT, err => {
if (err) throw err;
console.log(`> Ready and listening on http://localhost:${PORT}`);
});
}
}
start();
А на стороне атласа я:
Ушел под Доступ к сети и занес в белый список мой IP-адрес:
0.0.0.0 / 0
Я следовал документации по настройке атрибута Поиск , который, как мне показалось, был способом настройки Индексы
Не уверен, что проблема в том, что Atlas работал почти без настройки для развитие ...
Любая помощь будет оценена!