0

I'm creating a login system with React for frontend and Express for backend. I've already created the home, login and register page and when I run the app localy it works fine, but when I upload it to Heroku it breaks, e.g:

if I put this "http://localhost:3000/Register" in the browser, the Register page loads ok, but when I do the same in heroku's app, like this "https://twitterweb2.herokuapp.com/Register" then it breaks, it doesn't load and I get the "Cannot GET /Register" message. I'm concious I can handle this on the server side and it do may work, but why isn't working right now?

This is my React code:

import React from 'react';
import { BrowserRouter, Route } from "react-router-dom";
import Home from './pages/Home/Home';
import Raiz from './pages/Raiz/Raiz';
import Login from './pages/Login/Login';
import Register from './pages/Register/Register';
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <Route exact path="/" component={Raiz} />
      <Route exact path="/Register" component={Register} />
      <Route exact path="/Login" component={Login} />
      <Route exact path="/Home" component={Home} />
    </BrowserRouter>
  );
};

export default App;

And this is my server code:

var express = require('express')
const bcrypt = require('bcrypt')
const { Client } = require('pg')
const { response } = require('express')

var app = express()

const connectionData = {
  user: 'postgres',
  host: 'localhost',
  database: 'dblocal',
  password: '123456',
  port: 5432,
}

const client = new Client(connectionData)
client.connect()

const port = 3030;

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})
app.use(express.static('public'));

app.use(function(req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE");
  res.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Access-Control-Allow-Headers, Content-Type, Authorization, Origin, Accept");
  next();
});

app.use(express.json());
app.post('/pages/Register', async (request, responsee) => {
  const hashedPassword = await bcrypt.hash(request.body.password, 10);
  console.log(hashedPassword);   
  const data = request.body;

  client
    .query("select * from usuario where correo = '" + data.email + "'")
    .then(response => {
      if (response.rowCount>=1) {
        responsee.json({
          status: 'user already exists'
        });
      }
      else (
        client
          .query("insert into usuario (nombre, apellido, correo, usuario, passwordd) values ('"+data.name+"', '"+data.lastname+"', '"+data.email+"', '"+data.username+"', '"+hashedPassword+"')")                                
          .then(response => {
            responsee.json({
              status: 'user successfully created'
            })
          })
          .catch(err => {
            console.log("se ha creado exitosamente");
          })
      )
    })
    .catch(err => { })
});

app.post('/pages/Login', async (req, res) => {
  const hp = await bcrypt.hash(req.body.password, 10);
  client
    .query("select * from usuario where correo = '" + req.body.email + "'")
    .then (async response => {
      if (response.rowCount>=1) { 
        if (await bcrypt.compare(req.body.password, response.rows[0].passwordd))
          res.json({
            status: 'success'
          });
        else
          res.json({
            status: 'fail'
          });
      }
    });
});

5
  • 1
    I think your problem is that you didn't send the index.html to the client so react-router is not doing its job. Maybe this will help. Commented Dec 15, 2020 at 18:31
  • Thank you this solved the problem ! Commented Dec 15, 2020 at 22:23
  • Please approve the answer. Commented Dec 16, 2020 at 6:26
  • sure, but how do I do that? I already voted your answer as useful, isn't that what you mean? Commented Dec 16, 2020 at 16:57
  • The green tick must appear which means that the code works. Commented Dec 17, 2020 at 8:28

1 Answer 1

1

This may do the job:

app.get('*', (req,res) => {
  // just send the index.html file and point to its location :)
  res.sendFile(path.join(__dirname, 'public', 'index.html'))
})

Note that this entry point must be after all of your API resources.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.