简体   繁体   中英

React Router working locally but not deployed on heroku

I have ran my app on localhost and everything works fine, however once I deploy on heroku the home page works correctly, but when I hit "my-app/stocks/AAPL" I get a 404. I have looked at others with the issue and added a static.json file, but that does not help. I have pasted my code from my server.js, my folder structure, static.json, and my App.js for reference.

static.json

{
    "root": "client/build/",
    "clean_urls": false,
    "routes": {
      "/**": "index.html"
    }
  }

server.js

const stockRouter = require('./routes/stock')
const userRouter = require('./routes/user')
const express = require('express')
const path = require('path');
const mongoose = require('mongoose')
const cors = require('cors');

require('dotenv').config()
const app = express()


app.use(cors())
app.use(express.json())

mongoose.connect(process.env.MONGO_URI, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true});
const connection = mongoose.connection

connection.on('error', console.error.bind(console, 'connection error:'));

connection.once('open', function() {
  console.log('MongoDB connection successful')
});

app.use('/stock', stockRouter)
app.use('/user', userRouter)

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}

// for local env, use /client/public folder
else {
  app.use(express.static(path.join(__dirname, '/client/public')));
}

// server the client index.html file for all requests
app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname, "./client/public/index.html"));
});

app.listen(process.env.PORT || 5000, (req, res) => {
    console.log('Listening')
})

app.js

function App() {
  return (

    <Router>
      <ThemeProvider theme={theme}>
    <div className="App">
    <Container maxWidth='lg'>
      <Paper style={{ backgroundColor: '#f5f6f7'}}>
      <Nav></Nav>
      <Route exact path='/' component={StockTabs} />
      <Route exact path='/stocks/:symbol' component={StockInfo} />
      </Paper>
      </Container>
    </div>
    </ThemeProvider>
    </Router>
  
  );
}

file structure文件结构

When you hit the URL: my-app/stocks/AAPL , the default behavior of browser is sent a request to your server and you do not have the handler for that route on your server so 404 returns.

You have 2 ways to handle that case:

  1. Use HashRouter instead of BrowserRouter , your URL should look like:

    YOUR_SERVER:PORT/#/stocks/AAPL

The # on the URL does not trigger server call and routing will be handled by client entirely.

  1. You still can use BrowserRouter but it need to configure on your server, read on that post for more information: React-router urls don't work when refreshing or writing manually

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM