Home > database >  How to connect my front end to a NodeJS Backend that's deployed publicly and not on localhost
How to connect my front end to a NodeJS Backend that's deployed publicly and not on localhost

Time:10-17

I can connect them both when my NodeJS server is deployed on localhost PORT, for example

const PORT = 9000;
const app = express()
app.listen(PORT, () => console.log(`Server is running successfully on PORT ${PORT}`))
app.use(bodyParser.json({extended: true}))
app.use(cors())
app.use(bodyParser.urlencoded({extended: true}))
app.use('/', router)

And in my front end, I can do the following:

const url = 'http://localhost:9000'
...
const res = await axios.get(`${url}/post/${path}`)

This is just an example. But what if I wanted to deploy my NodeJS server into a heroku application, for example randomname.herokuapp.com, and I want to do

const url = 'http://randomname.herokuapp.com:9000'
...
const res = await axios.get(`${url}/post/${path}`)

It obviously doesn't work. So I'd appreciate anyone who can help me do this.

CodePudding user response:

Hello first of all if you deploy an app on heroku you will have to change port,you should add this to your code

app.listen(process.env.PORT || 3000,function(){
    console.log("Server started at ${PORT}");
});

because heroku will not deploy on the same port as you did on your localhost. Furthermore if i understand your question to link front with back end,in your code you should start building paths like

app.get("/")
app.post("/")

to handle get and post request to your home root and any other root. Also in your front pages you need to take user input,if you want text field,checkbox or something else in a form and take them in your back end ,if it is on your home page for example.

app.post("/home",function(req,res){
const input=req.body.name;
}

I have also deployed apps on heroku and the main idea still remains same,you handle get,post request with these commands.You only change port and Pocfile to run your app on heroku.Get and post routes still remain same ("/home ,/info").

The link for your app is going to be: "https://something_given_from_heroku.com" ,which will be given automatically from heroku.And you hit other routes like /home

I hope this help you,but check other posts to be sure.

CodePudding user response:

I've been doing this myself, instead of starting with barebones up to skeleton and onwards just download this base web app which you can immediately deploy to Heroku.. Link is https://github.com/hubspot/basewebapp

from there, initiate a repo on github from that link and deploy on Heroku via deployment and with automatic deploys, change on VSC or GitHub, changes apply to the webpage/webapp on Heroku.

If you need any other help, feel free to contact me.. Been surfing Heroku apps for a few weeks already.

Check www.conid.dev for as far as I've published so far

  • Related