'problem only in production: getting react index.html as response from some paths using react router and axios
problem only in production: getting react index.html as response from some paths using react router and axios.
When I deploy the app to heroku, I can post and get response from some routes but I have a problem with other routes.
For example, for route "get item list" Im getting this response in console.log : enter image description here (I`m not allowed to imbed pictures yet so the image is a link) data returned from back is index.html on " https://website/ home"
here is the main code parts :
ProductList.jsx:
const getProducts = () =>
axios
.get('/itemList')
.then((res) => {
console.log(res);
setProducts(res.data);
setFilteredProducts(res.data);
})
.catch((err) => console.log(err));
useEffect(() => {
getProducts();
}, []);
this is App.js:
import './App.css';
import React, { useState } from 'react';
import Header from './components/Header';
import ProductList from './components/ProductList';
import Dashboard from './routes/Dashboard';
import Home from './routes/Home';
import Login from './routes/Login';
import Footer from './components/Footer';
import SessionInfo from './components/SessionInfo.jsx';
import Register from './routes/Register';
import { Elements } from '@stripe/react-stripe-js';
import { loadStripe } from '@stripe/stripe-js';
import Check from './routes/Check';
import CircularProgress from '@material-ui/core/CircularProgress';
import { useAuth, AuthProvider } from './auth';
import { Link, useNavigate, Navigate } from 'react-router-dom';
import { BrowserRouter as Router, Routes, Route, Switch } from 'react-router-dom';
function RequireAuth({ children }) {
const { authed, checkSessionData } = useAuth();
const check = checkSessionData().then((r) => console.log(r, 'is check'));
return authed === true ? children : <Navigate to="/" replace />;
}
const stripePromise = loadStripe(
''// this is the key
);
function App() {
return (
<AuthProvider>
<div className="App">
<Elements stripe={stripePromise}>
<Router>
<div class="main-header">
</div>
</div>
<Routes>
<Route exact path="/check" element={<Check />} />
<Route exact path="/login" element={<Login />} />
<Route exact path="/register" element={<Register />} />
<Route
path="/dashboard"
element={
<RequireAuth>
<Dashboard />
</RequireAuth>
}
/>
<Route exact path="/home" element={<ProductList />} />
<Route exact path="/" element={<Home />} />
</Routes>
<Footer />
</Router>
</Elements>
</div>
</AuthProvider>
);
}
export default App;
routes.js
const express = require('express');
const itemListController = require('../controller/itemList.controller');
const userController = require('../controller/users.controller');
const sessionController = require('../controller/session.controller');
const requireUser = require('../middleware/requireUser');
const router = express.Router();
router.post('/itemList', itemListController.createItemList);
router.get('/itemList', itemListController.getItemsList);
itemListController.js
async getItemsList(req, res) {
try {
const id = await itemListService.getAllItems();
console.log('controller backend itemlist', id); // not showing even with mock array here
res.status(201).json(id);
} catch (error) {
console.log(error);
res.status(500).json('validation');
}
}
itemListService.js
getAllItems() {
return itemListDAO.getAllItems();
}
itemListdao.js
async getAllItems() {
const items = await db.select().table('items_list');
return items;
}
index.js index.html will show if the path cant be reache. thats why its showing me index.html.
require('dotenv').config();
const express = require('express');
const router = require('./routes');
const deserializeUser = require('./middleware/deSerialiseUser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const path = require('path');
const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
const port = process.env.PORT || 4000;
app.use(
cors({
credentials: true,
origin: 'http://localhost:3000',
})
);
app.use(deserializeUser.deserializeUser);
if (process.env.DB_ENVIRONMENT === 'production') {
console.log('test');
// Serve any static files
app.use(express.static(path.join(__dirname, '../front-end/build')));
// Handle React routing, return all requests to React app
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, '../front-end', 'build/', 'index.html'));
});
}
app.listen(port, () => {
console.log(`Server is running on ${port}`);
});
app.use(router);
this is the scripts
"scripts": {
"heroku-postbuild": "cd front-end && yarn && yarn build",
"start": "node src",
"build": "cd front-end react-scripts build",
"dev": "cd front-end react-scripts start",
"test": "cd front-end react-scripts test",
"eject": "cd front-end react-scripts eject",
"server": "nodemon src",
"migrate": "knex migrate:latest --knexfile src/db/knexfile.js"
},
-I tried changing the route in front to https:..heroukuapp.../itemList -I tried postman https:..heroukuapp.../itemList -I checked the heroku pg database and its there -I tried sending mock data
but it's not working.
Thank you in advance!H
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
