0

I created several routes that are working but my app.get('/') doesn't send anything from what I pass inside. Nothing happens in the backend console and so neither in the frontend when going on 'localhost:3000/' .. My front Home component is displayed fine on the '/' path... Any Idea what is going wrong in the back?

app.js (backend)

const  bodyParser  =  require('body-parser');
const app = express();
const morgan  =  require('morgan');
const connection = require('./helpers/db.js');
const session = require('express-session')

// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: false, saveUninitialized: false }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());


app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended:  false }));
app.use(bodyParser.json());
app.use(express.static(__dirname  +  '/public'));

app.get('/', (req, res) => {
  console.log('heeeeeeere')
  res.send('YOU ARE HERE')
  //res.render('YOU ARE HERE')
    //res.render('signup', { user: req.user });
  });


app.post('/signup', (req, res) => {
    var data  = {
        name: req.body.name,
        lastname: req.body.lastname,
        email: req.body.email,
        password: req.body.password
    };
     var email = data.email
     var passwordconf = req.body.passwordconf
     var password = data.password
     const checkEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
     checkEmail.test(String(email).toLowerCase())
     ? password === passwordconf 
         ?  connection.query('INSERT INTO users SET ?', data, (error, response, fields) => {
             if (error)
                 res.status(500).json({ flash:  error.message });
             else
                res.status(200).json({ flash:  "User has been signed up!" , path: '/profile'})
             })
         : res.status(500).json({ flash: "Please confirm your password again" })

     : res.status(500).json({ flash: "Please give a correct email" });
});


app.post('/signin', (req, res) => {
  var data  = {
      email: req.body.email,
      password: req.body.password
  };
   const checkEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
   checkEmail.test(String(data.email).toLowerCase())
       ?  connection.query(`SELECT * FROM users WHERE email = "${data.email}" AND password = "${data.password}"`, (error, response, fields) => {

        if (error)
               res.status(500).json({ flash: error.message});
           else
           response != '' 
           ? res.status(200).json({ flash:  "Welcome !", path: '/profile'})
           : res.status(200).json({ flash:  `The email or the password is incorrect`  , path: '/profile'})
           })
   : res.status(500).json({ flash: "Please give a correct email" });
});

// in case path is not found, return the 'Not Found' 404 code
app.use(function(req, res, next) {
    var  err  =  new  Error('Not Found');
    err.status  =  404;
    next(err);
});

app.get('/signin',
  function(req, res){
    res.render('login');
  });
  
app.get('/logout',
  function(req, res){
    req.logout();
    res.redirect('/');
  });

app.get('/profile',
  require('connect-ensure-login').ensureLoggedIn(),
  function(req, res){
    res.render('profile', { user: req.user });
  });


// launch the node server
let  server  =  app.listen( process.env.PORT  ||  5000, function(){
    console.log('Listening on port '  +  server.address().port);
});

Routes (frontend)

import {MuiThemeProvider} from '@material-ui/core/styles';
import { Grid, Paper } from '@material-ui/core';
import React from 'react';
import './App.css';
import {
  BrowserRouter as Router,
  Switch,
  Route
} from "react-router-dom";
import SignUp from './components/SignUp';
import SignIn from './components/SignIn';
import Profile from './components/Profile';
import Home from './components/Home';

// const bcrypt = require('bcrypt');


function App() {
  return (
<MuiThemeProvider  >
    <Grid  container
    alignItems='center'
    style={{ height:  '100%' }}>
      <Grid  item  xs={12}>
        <Paper
        elevation={4}
        style={{ margin:  32 }}
        >
          <Grid  container
          alignItems='center'
          justify='center'>
              <Grid item  xs={12}
              alignContent='center'
              >
                <Router>
                  <Switch>
                  <Route path='/'>
                      <Home />
                    </Route> 
                    <Route path='/signup'>
                      <SignUp />
                    </Route> 
                    <Route path='/signin'>
                      <SignIn />
                    </Route>     
                    <Route path='/profile'>
                      <Profile />
                    </Route>                
                  </Switch>
                </Router>
              </Grid>
          </Grid>
        </Paper>
      </Grid>
    </Grid>
</MuiThemeProvider>
  );
}

export default App;
Julie
  • 17
  • 6
  • so does `console.log('heeeeeeere')` not get printed in your conosle? – ZombieChowder Jul 01 '20 at 10:13
  • 2
    You are listening on PORT 5000. So how will it get executed on localhost 3000. let server = app.listen( process.env.PORT || 3000, function(){ console.log('Listening on port ' + server.address().port); }); – Jatin verma Jul 01 '20 at 10:13
  • Maybe they are running with `PORT=3000`... – CherryDT Jul 01 '20 at 10:20
  • Only the route get('/) doesn't work, all the others do. So it doesn't seem to be a port issue... I am listening to port 5000 for the backend and to port 3000 for the frontend. Nothing happens in the backend console just as in the frontend console. – Julie Jul 01 '20 at 12:39

2 Answers2

0

It sounds like some confusion regarding your frontend and backend. I see two possible reasons for your problem:

  1. Either you are indeed looking at http://localhost:3000 (where supposedly your frontend is running) while your backend is running at http://localhost:5000. In that case, you'd have to look at http://localhost:5000 to see your backend responding.

    (In a real use case, your frontend would send API requests to your backend and you wouldn't browse to it manually.)

  2. Or you just confused the ports in your post (or you are running with environment variable PORT=3000 set), and your frontend and backend listen on the same port, with your backend serving the frontend using express.static. In this case the issue is most likely that you have an index.html in your public folder, and since the express.static middleware is above your app.get('/'), it takes priority.

    In this case you can move the / route above express.static. If you want to serve your signup page there only sometimes (for example when the user is not logged in), you could use the next argument in your route handler and call next('route') to "fall through" to the next handler (your static file server) if the user is actually logged in. See this answer.

CherryDT
  • 13,941
  • 2
  • 31
  • 50
  • Only the route get('/) doesn't work, all the others do. So it doesn't seem to be a port issue... I am listening to port 5000 for the backend and to port 3000 for the frontend. Nothing happens in the backend console (nor a simple console.log) just as in the frontend console (of course as it doesn't work in the backend) – Julie Jul 01 '20 at 12:42
  • 1
    I don't understand what you are saying. If you open localhost:3000 and the backend is listening on localhost:5000, why do you expect anything to happen in the backend unless you have an API call in your frontend to the backend (which you didn't show here)? – CherryDT Jul 01 '20 at 13:24
  • On second glance, it seems like you really have a big confusion here with backend and frontend, because you seem to have the same routes both in the frontend and the backend, and both of them render HTML, which doesn't make sense to me right now. For example, when you go to http://localhost:3000/signup you will see the frontend signup route (the backend does nothing), and when you go to http://localhost:5000/signup you will see the backend signup route (the frontend does nothing). That doesn't sound right. – CherryDT Jul 01 '20 at 13:26
0

you may have to specify exact in your react frontend when using BrowserRouter. it may be matching all routes if exact is not specified?

something like below?

<Route path='/' exact>
    <Home />
</Route>

explanation here - React : difference between <Route exact path="/" /> and <Route path="/" />

Raj
  • 124
  • 5
  • Thank you for the answer. Unfortunately It doesn't work neither.. – Julie Jul 01 '20 at 12:34
  • 1
    hey @Julie like @CherryDT mentioned, you have the frontend and backend setup, however the connection might be missing. In your individual components, for example `signup` you may have to do a call to your backend server so that backend code will be triggered – Raj Jul 02 '20 at 00:23