Heroku url routes can only be reached programmatically - javascript

Sorry if this question is vague but I really don't know what code to present.
I have a Heroku webpage which is running fine. I am using reach-router to navigate from one page to another on button clicks: <button onClick={() => navigate('/intro')}>Click</button>. When I do this the url changes appropriately and my content is visible. However if I type in the exact same url I get an error saying Cannot GET /intro. This error even happens if I use the button click to navigate and then reload the page.
It's my understanding that app.use(express.static('build')); will serve my static files.
So why can I visit pages if I start at my root url and navigate from there but I can't enter a url and travel to that page?
The website is live here https://build-a-wedding.herokuapp.com/
Adding more details on my server.js
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const cors = require('cors');
const sessionMiddleware = require('./modules/session-middleware');
require('dotenv').config();
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(sessionMiddleware);
app.use(cors());
// Serve static files
app.use(express.static('build'));
app.use(express.static(path.resolve(__dirname, '..', 'build')));
const users = require('./routes/users.router');
const dataFetch = require('./routes/data.router');
const venues = require('./routes/venues.router');
app.use('/users', users);
app.use('/location', dataFetch);
// app.use('/', auth);
app.use('/venues', venues);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Listening on port: ${PORT}`);
});
When I navigate programmatically here is what i see for my sources
When I type in the same URL here is the source tree

Just create a static.json file at the root of your React project with the following content:
{
"root": "build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
This question is possibly duplicated

Make sure that your express app are listening to these routes and sending response to them.
Example:
app.get('/intro', function (req, res) {
res.send(pathToPage);
});

Related

Node.js server running but not loading on browser

I know this is a simple problem but I have been looking for a solution for the last 2 days and can't seem to find it. I am following a tutorial where we've set up an express server. I think the two relevant files are app.js and auth.js.
APP.js
//PACKAGES
//"mongodb://0.0.0.0:27017/test"
require('dotenv').config()
const mongoose = require('mongoose')
const express = require("express")
const app = express()
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
//LOCAL PACKAGES
const authRoutes = require("./routes/auth")
//CONNECTING TO MONGODB
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true
}).then(() => {
console.log(`DB CONNECTED!!!!!`)
})
//MIDDLEWARE
app.use(bodyParser.json)
app.use(cookieParser())
app.use(cors())
//ROUTES
app.use("/api", authRoutes)
//PORT
const port = process.env.PORT || 8000;
//STARTING A SERVER
app.listen(port, ()=> {
console.log(`app is running at ${port}`)
})
AUTH.js
const express = require('express')
const router = express.Router()
router.get("/signout", (req,res)=> {
res.send("user signout")
})
module.exports = router;
In the console, I see that my server is connected to DB and running on port no 8000
However, when I go to the browser and write http://localhost:8000/api/signout, a spinning wheel that never stops and it does not return my request. I have tried to match the author's code, turn off the firewall, and changed the port number but nothing works. I would be grateful if someone helps as I am stuck on this problem and I want to progress. Thank you!
P.S: my github repo: https://github.com/timothyroybd/ecommerce-website
There is a problem with usage of body-parser.
You have app.use(bodyParser.json)
and should be app.use(bodyParser.json())

post request 404 NOT FOUND after hosting website

So I just hosted a website with Network Solutions and when I try to use the contact form on the site, a 404 error appears. I am aware that something is not configured correctly. What do I need to change in my code? I use Node.js and React.
Error: POST http://www.example.com/api/contact 404 (Not Found)
Port 80 doesn't work...
My index.js file:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { contact } = require('./contact');
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
app.post('/api/contact', contact);
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Do I need to change the PORT code to something else?
I am not aware of how Network Solutions works but the problem is most probably is your port. Check out what is the process.env.PORT (from node console.log) and if it is in 3001 port make sure that port is accessible and not blocked by firewall.

node.js/express/ejs not rendering root page?

I'm using node.js, express, and ejs as a development environment. I've run into an issue where my main page isn't rendered. However, other pages are rendered. I get absolutely no return when I access http://127.0.0.1:9999. However, I get the proper response when I access http://127.0.0.1:9999/about. I replaced my normal page with a very simple test page to check if there was something wrong it. Nope. No change. I can only conclude that the path '/' (or '') isn't seeing the request.
Can anyone see the problem? Thanks
app.js
const path = require("path");
const express = require("express");
const ejs = require("ejs");
const app = express();
const port = 9999;
const viewsPath = path.join(__dirname, "./views");
app.set("view engine", "ejs");
app.set("views", viewsPath);
app.use(express.static(path.join(__dirname, "/public")));
app.get("/", function(req, res) {
console.log("index accessed");
res.status(200).render("partials/test.ejs");
});
app.get("/about", function(req, res) {
console.log("about accessed");
res.status(200).render("partials/test.ejs");
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
test.ejs
<h1>This is a test page</h1>
I added the following route, and the path is not matched.
app.get("*", function(req, res) {
console.log("* accessed");
res.status(200).render("partials/test.ejs");
});
In the meanwhile it is possible to use:
app.use(express.static(app_path, {
index: false
}));
Credits to

Node server response is HTML after adding catch-all to allow react-router to work

I have been developing a node backend, react front end web app for a couple months. It has working just fine when I started the server via nodemon and the front end with npm start. But now that I am getting ready to host an alpha version and ran 'npm run build' I've been running into issues.
It seems to be stemming from the interaction of accessing the app from the server's port and react-router. I added a catch-all endpoint app.get('/*'...) to my server to allow the react-router to work. So now when the front requests data, the response is HTML not the array I want.
I feel like there is a simple solution to this, but I just don't see it yet. I looked into using HashRouter instead of BrowserRouter, but unfortunately I can't use that because I am using MSAL Active Directory for login.
server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
require('dotenv').config();
const massive = require('massive');
const session = require("express-session");
const morgan = require('morgan');
const path = require('path');
const ctrl = require(`./controllers/controller.js`);
//Middleware
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(express.static(__dirname + './../build'));
app.use(morgan('dev'));
//Connection to Azure DB
massive(process.env.CONNECTION_STRING)
.then(db => {
console.log('Connected to Azure PostgreSQL Database')
app.set('db', db)
}).catch(err=>console.log(err))
app.use(session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: true
}));
//Endpoints
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
app.get('/getallemployees/', ctrl.getAllEmployees)
app.listen(8080, () => console.log(`Listening on ${8080}`));
Put that catch-all endpoint after all the others that return data.
//Endpoints
app.get('/getallemployees/', ctrl.getAllEmployees)
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})

How to serve an image from Express.js to React

I am trying to serve up an image from my public directory on my node.js + express backend to the client side which is Reacts (create-react-app to be particular).
I have the typical file structure of
-public
-images
-image.jpeg
On my client side, I have an image tag with a relative path like so
<img src='/images/me.jpeg' alt="" />
My app.js for express looks like so
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const contactRouter = require('./routes/contact');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + "/public"));
app.use(express.static(path.join(__dirname, 'client/build')));
//route handlers
app.use('/contact', contactRouter);
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
module.exports = app;
alas, I am not getting any luck with the image being served up. Any ideas for this? I am not sure if I also need an additional proxy for when I am in dev. I have tried this which likes in my src folder in react
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(proxy('/images/*', { target: 'http://localhost:5000' }));
}
I appreciate the help guys!

Categories