0
votes

I used this https://medium.com/weekly-webtips/create-and-deploy-your-first-react-web-app-with-a-node-js-backend-ec622e0328d7 to create React Front End and NodeJS backend. On running locally, it worked but I deployed it on Heroku. I didn't receive any response from express server api.

app.get("/test/", (request, response) => {
    response.send({"name":"Hello Test!!!"});
});

my proxy setting looks like this

Result in http://localhost:3000/

Hello from the frontend! Hello Test!!!

Result in https://react-node-js-test.herokuapp.com/ Hello from the frontend!

"proxy": "http://localhost:5000",

server.js

// Import dependencies
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');

// Create a new express application named 'app'
const app = express();

// Set our backend port to be either an environment variable or port 5000
const port = process.env.PORT || 5000;

// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
    console.log(`Request_Endpoint: ${req.method} ${req.url}`);
    next();
});

// Configure the bodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

// Configure the CORs middleware
app.use(cors());

// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
    app.use(express.static(path.join(__dirname, 'client/build')));

    app.get('*', function (req, res) {
        res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    });
};

// // Catch any bad requests
// app.get('*', (req, res) => {
//     res.status(200).json({
//         msg: 'Catch All'
//     });
// });

app.get("/test/", (request, response) => {
    response.send({"name":"Hello Test!!!"});
});

// Configure our server to listen on the port defiend by our port variable
app.listen(port, () => console.log(`BACK_END_SERVICE_PORT: ${port}`));

Any help would be great

1
can you add the whole API file or where you're initializing the server and make sure you've initialize the server port like this, let PORT = process.env.PORT || 5000; - Akshay Pagare
@akshay added the server.js file - Ankita Jaiswal

1 Answers

0
votes
// MOVE THIS BEOFRE get("*") 
// Because * will handle all incoming requests

app.get("/test/", (request, response) => {
    response.send({"name":"Hello Test!!!"});
}); 

// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
    app.use(express.static(path.join(__dirname, 'client/build')));

    app.get('*', function (req, res) {
        res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    });
};