У меня странная проблема, когда мой сервер просто перестал отвечать. Также nodemon
перезагружается все время, если я не делаю nodemon app.js
.
Это работало раньше, и я не знаю, что я испортил.
app.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const {db,} = require('./config/db');
const app = express();
mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('connected'))
.catch((e) => console.log(e));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false,}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './views')));
app.use(bodyParser.json());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use((req, res, next) => {
next(createError(404));
});
app.use((err, req, res) => {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Я пытался просто GET
a localhost:3000
. 3000 правильный порт. Я тоже пробовал 8080 и другие. Не повезло.
Я добавил console.logs по всему файлу, и они все запустились. Я добавил console.logs пользователям и индексным маршрутизаторам, и они оба загружены.
Есть идеи?
Изменить.
bin/www
file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort('3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
routes/index.js
const express = require('express');
const router = express.Router();
const path = require('path');
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
module.exports = router;
routes/users.js
const express = require('express');
const passwordValidator = require('password-validator');
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const UserSchema = require('../models/user');
const router = express.Router();
router.get('/', (req, res) => res.text(1));
router.post('/register', async (req, res) => {
const {email, password, passwordRepeat,} = req.body;
const errors = [];
// eslint-disable-next-line
if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
errors.push('Email is invalid');
}
const isUserRegistered = await mongoose.findOne({email,});
if (isUserRegistered) {
res.json({errors: ['User is already registered',], ok: false,});
}
if (password !== passwordRepeat) {
errors.push('Passwords do not match');
}
// eslint-disable-next-line new-cap
const schema = new passwordValidator()
.is().min(8)
.has().digits()
.has().lowercase()
.has().uppercase()
.has().symbols();
if (!schema.validate(password)) {
errors.push('Password is invalid');
}
if (errors.length > 0) {
res.json({errors, ok: false,});
} else {
const UserModel = mongoose.Model('User', UserSchema);
UserModel.create({email, password: bcrypt(password, 12),});
res.json({ok: true,});
}
});
module.exports = router;