Route handlers not working properly in express server (Create react app) - node.js

I have a simple react app made with CRA, and I deployed it on vercel. Everything seems to be working with one exception. My route handlers are not sending back the correct response. It seems like they are sending the index.html file that is created from the build script. I'm not really sure why this is happening. It sent the correct response when I built it locally. Here is the code for the express server:
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "build")));
app.get("/ping", function (req, res) {
return res.send("pong");
});
// app.get("*", (req, res) => {
// res.sendFile(path.join(__dirname, "build", "index.html"));
// });
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
And here is the file structure if that helps:

I figured out the issue. Vercel only supports serverless deployment. You can't host an express server, just a static site

Related

find the error while deploying the node.js app to server

I found the error while deploying the node app on the server. the index.js file code
const connectToDb = require("./DBconfig");
const express = require('express')
const router = express.Router();
var cors = require('cors');
connectToDb();
const app = express();
const port = process.env.PORT | 5000;
app.use(cors());
app.use(express.json());
connectToDb();
app.use( '/api/user' ,require('./routes/user') );
app.use( '/api/post' ,require('./routes/post') );
app.get('/', (req, res) => {
res.send('The site is start now')
})
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.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
when I deploy the app and install the node in the server like how I install the node in server I attached the picture in which I show the installation of the node. and above I add the index.js code. It works properly in the local machine but if I hit the URL of backend backendURL it show the service unavailable error message kindly give me the solution to solve this problem.

My app works locally but on Heroku I'm just getting the React logo

When I run my app locally it works just fine. I deployed my app on Heroku and the build was successful without any errors. However, whenever I open the app, I just get the revolving React icon page that you get when you first create a react app. I'm getting nothing in the console and the Heroku log is giving me back status 200 so I'm not sure what's going on.
I notice it has something to do with my build folder because when I delete the app returns "Not Found".
I believe its in my server.js file.
require("dotenv").config();
const express = require('express');
const port = process.env.PORT || 8080;
const path = require("path");
var app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
if(process.env.NODE_ENV === "production"){
app.use("*", function(req, res){
res.sendFile(path.join(__dirname, "/client/build/index.html"));
})
}
app.listen(port, (req, res) => {
console.log(`server listening on localhost:${port}`);
});
I just tried copying over from an app that I did successfully launch on heroku. I'm fairly new to coding so I don't even know what half of it means. If someone could help me out, that would be greatly appreciated.
That's probably because you are using create-react-app and you're not serving the /build folder. You can easily add an express server to do it.
First, install the express module:
npm install express --save
And the add a server.js file that will serve your /build/index.html on all requests:
const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build/index.html'));
});
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}`);
});
I figured it out. I didnt have a build script in my package.json

Node.js - Specifying URL in Heroku yields internal server error, running locally works fine

I'm having some issues with my application after it's been deployed to heroku. When I specify the URL, or refresh the browser on a page OTHER than the homepage I am getting an "Internal Server error" and the page doesn't load. However when I click the links which naviagte me to those pages from the home page it works fine. When I run the server locally it does not give me this error.
Based on my research this is probably an error on the server side. Here is my code:
Node.js backend
const express = require("express");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const actions = require("./routes/api/dbActions");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/dbActions", actions);
// Serve static assets if in production
if (process.env.NODE_ENV === 'production') {
// Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port} !`));
Any idea why this might be happening?
Thanks!!
In my server.js file I included the following:
const path = require('path');
Which seems to have worked for me.

Accessing express routes on heroku directly without serving the react app

Express routes can not be reached directly without serving the react-app on heroku.
I have developed a react-app that runs with a node.js / express backend on heroku. Everything within the react-app works fine.
Now i need to access an express route (e.g. https://example.com/api/info) that makes a call to a mongo db and should only return some JSON.
The problem is, that express always serves the react-app. From within the react-app i can however access the express routes and use them for e.g. login/signup (https://example.com/api/users/login). I just can't access them in production on heroku directly without serving the react-app.
Since heroku decides the port on which the express app lives i can't add a proxy to the react-app's package.json
The react-app is build in the root>client folder.
Please find below the root index.js file of the node.js / express server
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const keys = require('./config/keys');
const auth = require('./routes/api/auth');
const mail = require('./routes/api/mail');
const newsletter = require('./routes/api/newsletter');
//connect to mongoDB
mongoose.connect(keys.mongoURI)
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
const app = express();
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Passport Config
app.use(passport.initialize());
require('./services/passportJwt')(passport);
// Routes
app.use('/api/users', auth);
app.use('/api/mail', mail);
app.use('/api/newsletter', newsletter);
app.get('/api/info', (req, res) => { //ROUTE DOESN'T WORK, SERVES REACT-APP
res.json({ msg: "Some Info" });
});
// Serve React App in Production
if (process.env.NODE_ENV === 'production') {
// Express will serve up production assets, main.js/main.css
app.use(express.static('client/build'));
// Express will serve up the index.html file if it doesn't recognize the route
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
// Use Heroku port or 5000 when in dev
const PORT = process.env.PORT || 5000;
app.listen(PORT);
Expected result:
When reaching "https://example.com/api/info" a JSON output should be received { "msg": "Some info" }.
Instead the react-app is served and the react-app doesnt recognize the route "api/info" within the react-router.
Thanks in advance for your help.

Angular 7 Service Worker not Working Offline when using Node.Js Server

I have an Angular 7 project with PWA functionality added.
I basically have all PWA-related settings set to default.
My issue is, that offline mode does not work when deploying the project to my server. It's also not working when starting the server on localhost.
However, when using the npm module http-server to host the app on localhost, the offline mode works.
Online the service worker is applied:
Here is what happens when loading app offline:
The code of my Node.Js server looks like this:
require('module-alias/register')
const express = require('express')
const app = express()
const prod = require('#root/prod')
const port = process.env.PORT || 3000
const path = require('path')
const compression = require('compression')
app.use(compression())
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(path.join(__dirname, '../client/dist/client')));
const api = require('#root/api/api.routes')
app.use('/api', api)
app.get('*', (req, res) => {
res.status(200).sendFile(path.join(__dirname, '../client/dist/client/index.html'))
})
app.use(function (err, req, res, next) {
console.log('error occured', err.stack);
res.status(500).send({ "Error": err.stack });
});
app.listen(port, () => {
console.log(`• • •`)
console.log(`• Server launched 🚀 on port`, port)
console.log(`• Server running in ${prod ? '🔥 production' : '💉 development'} mode`)
console.log(`• • •`)
})
Here are all files from the production build:

Resources