jeudi 14 juillet 2022

Should I improve something in this Node.js code? Iam newbie please help me I can't sign up my webapp that Iam creating (error 404 server) [closed]

I just want to make sure that this is the right code for using node.js ? or am i missing something ? Iam not tough backend guy please suggest me

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');

mongoose.connect(
  process.env.MONGO_DB_URI,
  { useNewUrlParser: true, useUnifiedTopology: true },
);


const usersRouter = require('./routes/users');
const listRouter = require('./routes/list'); 
const databaseRouter = require('./routes/database');

const publicPath = path.join(__dirname, 'build');

const app = express();
app.use(cors());


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// I just import my logic 
app.use('/users', usersRouter);
app.use('/database', databaseRouter);
app.use('/list', listRouter); 

app.get('*', (req, res) => {
  res.send(path.join(publicPath, 'index.html'));
});


app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res) => {
 
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and file that I want to execute (have shabang -> #!/usr/bin/env node )

const app = require('../app');
const debug = require('debug')('backend:server');
const http = require('http');
 


 
//Create HTTP server
const server = http.createServer(app);
 
 
  //Get port from environment and store in Express
const port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
 //Normalize a port into a number, string, or false
function normalizePort(val) {
   const port = parseInt(val, 10);
 
   if (isNaN(port)) {
     // named pipe
     return val;
   }
 
   if (port >= 0) {
     // port number
     return port;
   }
 
   return false;
 }
 
  //Listen on provided port, on all network interfaces
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


//This function will check which type of error occurred,
// log something different, and exit gracefully from our nodejs server.
function onError(error) {
   if (error.syscall !== 'listen') {
     throw error;
   }
 
   const bind = typeof port === 'string'
     ? `Pipe ${port}`
     : `Port ${port}`;
 
  
   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() {
   const addr = server.address();
   const bind = typeof addr === 'string'
     ? `pipe ${addr}`
     : `port ${addr.port}`;
   debug(`Listening on ${bind}`);
}

Any mistake that I made please correct me or want some information that need to show please tell me. Thankyou

Aucun commentaire:

Enregistrer un commentaire