0

I am trying to deploy reactjs & nodejs app to heroku. I have successfully deployed frontend,but frontend is sending data to nodejs using localhost due to which when running app through heroku only frontend is working.

This code send data to nodejs.

saveUserJson = (User) =>{
    const url = 'http://localhost:5000/write'
    axios.post(url,User)
    .then(response => {
        //console.log(response);
    });
  }

This is nodejs code(ignore hostname in code).

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const morgan = require('morgan');
const cors = require('cors');
const jsonData = require('../src/descriptors/bnk48.json')

const app = express();
const port = 5000;
const hostname = '192.168.43.113';

app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());

app.get('/',(req,res) => res.status(200).send({
    message: "Server is running..."
}));


const WriteTextToFileSync =  (contentToWrite) => {
    fs.writeFileSync('./src/descriptors/bnk48.json',contentToWrite,(err) =>{
        //console.log(contentToWrite);
        if(err) {
            console.log(err);
        }else {
            console.log('Done writing to file successfully...')
        }
    })
}
const user = {

}
app.post('/write',(req,res,next) =>{
    const user = {
        "name": req.body[0].name,
        "descriptors": req.body[0].descriptors
    }
    jsonData[user.name]=user
    //console.log(req.body[0].descriptors)
    const requestContent = JSON.stringify(jsonData,null,2);
    WriteTextToFileSync(requestContent)
});

app.use((req,res,next) => res.status(404).send({
    message: "Couldn't find specified route that was requested..."
}));

app.listen(port,hostname,()=>{
    console.log(
        `
        !!! server is running..
        !!! Listening for incoming requests on port ${port}
        !!! Server running at http://${hostname}:${port}/
        !!! http://localhost:5000
        `
    )
})

How can i change localhost so that while deploying it automatically chooses where to send data?

1 Answers1

1

How can i change localhost so that while deploying it automatically chooses where to send data?

There are several ways to do this, but it's quite common to use environment variables for this purpose. These are set by environment, your development machine being one environment and your production site on Heroku being another environment. You could for example define the environment variable BACKEND_ROOT_URL to hold the schema and FQDN of your site, and make your axios call like this:

saveUserJson = (User) =>{
    const url = `${process.env.BACKEND_ROOT_URL}/write`
    axios.post(url,User)
    .then(response => {
        //console.log(response);
    });
  }

The build-time value of url will be different, depending on which environment you perform the build in.

Setting environment variables locally can be done in several ways. In a Bash shell you can set them manually like export BACKEND_ROOT_URL=http://localhost:5000. That get's boring quite fast though, so I would recommend you to check out dotenv which handles this for you efficiently.

Heroku has its own way of handling the setting of envvars - check the documentation here

Gustav
  • 477
  • 4
  • 8
  • Do i need to change anything from backend code(nodejs code)? –  Dec 07 '20 at 06:24
  • I do not myself often deploy to Heroku, so I don't really know how it handles IP/domain name and port setting. I typically don't have to hardcode `hostname` or `port` in the `Application.listen()` method. The port is often present as an environment variable `PORT` too. If your backend code doesn't serve requests when you deploy, I would try to change the `listen` method to something like: `app.listen(process.env.PORT || 5000, () => {}` See also [this thread](https://stackoverflow.com/questions/28706180/setting-the-port-for-node-js-server-on-heroku) – Gustav Dec 07 '20 at 13:57