Frontend to backend request seems to be wrong - node.js

Hi I am trying to deploy a simple React + Node app to a remote server. Backend started with pm2 and seems ok, frontend works with nginx, but when I try to get data from the db, console sends message
GET http://localhost:8080/v1/names net :: ERR_CONNECTION_REFUSED xhr.js: 177
Not too sure if I need to replace request url with the server IP instead of localhost.
Any help is greatly appreciated.

Yes, you should change all your request from localhost to your deployed address, I would also propose you take a look at .env Files to do it. Node.js Everywhere with Environment Variables!.
usually, you should use .env files to automatically choose the good address when deployed and when coding locally. have a nice day.
example of code with a .env file from the back with mongoose.
mongoose
.connect(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0.qvs4c.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
)
.then(() => {
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), function () {
console.log("Node app is running on port", app.get("port"));
});
})
.catch((err) => {
console.log(err);
});
example of my .env File.
DB_USER=thatsmydbuser
DB_PASSWORD=thatsmypassword123!
DB_NAME=thatsmydbname

Related

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

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.
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.
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

Chat with another pc with react chat-app and socket.io

I followed a youtube tutorial on making a chat app with react js and socket.io. It is complete and works perfectly, but only on the pc, the project is running on. What I need is the application to chat with another pc the project is working on, it could be on the same network, for starters. The front-end is separate and is made with react js.
I tried adding a dummy IP to where I specify the port it will run on, but didn't work.
Any ideas? What am I missing here?
Here's the code to the server.js which is in plain node js:
const port = 5000 || '0.0.0.0' <--- Ignore the dummy IP kindly, didn't work, thought it was worth a try
const io = require('socket.io')(port)
io.on('connection', socket => {
const id = socket.handshake.query.id
socket.join(id)
console.log("Listening at " + port)
socket.on('send-message', ({ recipients, text }) => {
recipients.forEach(recipient => {
const newRecipients = recipients.filter(r => r !== recipient)
newRecipients.push(id)
socket.broadcast.to(recipient).emit('receive-message', {
recipients: newRecipients, sender: id, text
})
})
})
})
I'd recommend you look into deploying your chat app on something like Heroku or Firebase, which will provide you a 3rd-party non-localhost link that other PCs and users can go to in order to access your chat app.
Alternatively, you can use something like https://github.com/localtunnel/localtunnel to have other PCs access your localhost

App.listen on an already running port of shared hosting

var express = require('express');
var app = express();
app.get("/", function(req,res){
console.log("running on that weird path i made///");
res.send("HELLO THIS IS A WEBPAGE TRYOUT!");
});
app.listen(3000, function(){
console.log("Server running on 3000");
})
I’m trying to create a simple app (for practice) which does a simple hello world. Using express via node.js
I can do it locally no problems.
The problem is I’m trying to run it on an existing server using cPanel shared hosting.
And there is obviously an already running domain name(and has website installed in Wordpress), so I cannot do a simple app.listen to a port which is obviously already running. And I’m guessing therefor I cannot do app.get(“/“....)
I’ve tried a different port-but the get request won’t work(I think obviously since that’s not the one running?)
So when I tell it to listen to the cPanel port, it throws an error that it’s already running.
And I don’t want to stop from the website to run. Is there a way to work this?
Tried also using subdomains. Same result.
Edit:
this worked on postman, when I've sent a get request to that address. tried port 3000, and it showed my res.send on the postman tab.
Edit2:
I've solved this...i forgot to put :3000 on the address..
as in www.example.com:3000
this doesn't work if i don't add the :3000.
and also if i do process.env.PORT and .IP..guessing its because its a shared hosting, or because wordpress is installed...
I won't delete just in case anyone did the same mistake as me.
If the problem that the port is already in use, you may try to use 0 as a port that will cause it to take a random free port on the machine.
const server = app.listen(0, function(){
console.log(`Server is listening on http://localhost:${server.address().port}`);
})

Access dynamic port number in Webpack

I'm building an electron/nodejs/react application that will run on a users localhost (e.g. localhost:8080).
I'm using Portfinder to locate a free port and run the application on that port.
portfinder
.getPortPromise()
.then(port => {
app.listen(port, function() {
console.log("Server started on localhost:" + port + ", Node ENV " + app.get("env"));
});
})
.catch(err => {
//Could not get a free port, `err` contains the reason.
});
In the React app, I need to access this port number to send http requests back to the node server.
Is there a way to access this dynamically created port # in React or Webpack outside of using env variables in package.json or .env file?
If the same server is used for serving client and backend APIs, then you can use relative routes (/api/getData). The client will hit the same server.
If your backend is hosted on a different server, then you need to pass the information to client manually.

Trying to run node app on fedora server

Ok I am making website and want to use mongo, express, etc. I setup a server using fedora server ISO. The problem is getting node working. I have followed several tutorials, and its all the same. Nothing works. So I have to be doing something wrong. Trying to get the simplest thing to display on screen.
I think the server is running httpd server, whatever fedora has built in. I get the default fedora server page when going to the url. So the server is running and working, just hasn't been configured. When running node on the server do I have to use httpd-node? Or can it be http, etc.
Here is my app.js
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
And then I have a basic index.html that should be rendered just saying test.
I ssh into the server and run node start, it runs and the console logs the message like it should. But if I go to the address 192.168.1.5, or the domain that points to the server, I get nothing, just a blank page.
If someone can help me get this working, I can actually get to work coding out the application. Any help would be appreciated.
I think you make a confusion. When you build an Express application, you do not need another server at all.
When you start your app with:
app.listen(3000, function () {})
Express returns an http.Server object listening to port 3000.
When you navigate to your local adress on port 3000, you will see your "hello world" message.
It is possible that httpd service is already running in your Fedora environnement on default port 80 (the default port for http, the one your reach when you go to your local adress) but this is an Apache server and you do not need it to run your Nodejs app.
To build a Nodejs server, you can also use httpd-node package, but this is redundant as you're using Express framework.
If you need to serve a simple html file, a method I like for its simplicity is to use ejs template engine, something like this.
res.send('Hello World!') - this is your problem! Why?
How you receive this answer on client side?
Solution: use res.render(..) - for rendering from server or use AJAX on client side for receive this text!
P.S: render page and you don't see blank page anymore! Or use client-server conversation logic with your server through AJAX.
Try 192.168.1.5:3000
If I wrong: show your full project setup...
Test your app with curl (https://curl.haxx.se)! Check connection establishment, and show results here!

Resources