React-app frontend & express backend using nginx on ubuntu - javascript

I have been searching google for a couple of hours, been through multiple pages, and watching youtube videos but I am simply not able to find any guidance towards what to do in my case.
I have a react-app frontend running on Nginx.
With the frontend react-app I am running some Axios requests, example:
await axios.post("http://localhost:5000/api/getMessages", {});
I then have my express server receiving the requests and sending back responses, example:
app.post('/api/getMessages', (req, res) => {
Messages.find().sort('-createdAt').limit(10)
.then((result) => {
res.send(result)
})
})
Everything works fine in my local environment, but I am unsure of what to do when putting it on a live server with a domain using Nginx. I am able to get the react-app up and working just fine, but when making an axios request it simply returns net::ERR_CONNECTION_REFUSED
This is with my express server running in the back like a normal node project.

You must add rule for your server's ufw.
Ufw rule adding

Related

How to connect a frontend application on a different port with a backend?

I put my frontend application in the public folder for a node.js application and am getting the form-data using the following request:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
My backend is in port 5000 and it's handling the request by:
app.use("/api/v1/contact-form", submitFormRouter);
It works perfect. I'm getting the data when I have my frontend application is in the node.js public folder.
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I replace the following path for post:
Frontend:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
Backend:
app.use("/api/v1/contact-form", submitFormRouter)
I've also tried the code using React in which case the frontend is running in http://localhost:3000/ and node.js server running in 5000, the code still works and I'm getting the form data. But, how do I make it work for a frontend application sitting in a different port(without react)?
Additionally, I hope you're kind enough to answer the following question- What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
Let's assume your Back on Heroku has this url https://app.herokuapp.com/ and the Front on Netlify this one https://app.netlify.com/. All you have to do is to give your Front your Back's url, like so:
try {
await axios.post("https://app.herokuapp.com/api/v1/contact-form", {
name,
email,
msg,
});
}
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I...
At this point you have two choices, the simplest one is to use a complete url like above. Let's assume your Front is on port 3000 and the Back on 8080. All you have to do again is:
try {
await axios.post("http://localhost:8080/api/v1/contact-form", {
name,
email,
msg,
});
}
The second one is to use a proxy, and this really depends on your projects' structure and need.

NodeJs: How do I access the functions of my JavaScript backend from my HTML frontend?

Here is my HTML code in index.html.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?
You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.
If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)
Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.
To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.
If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.

Is there anyway that I can get the running port?

I`d like to show in my React application the running port of the local server, is there any way to get it programmatically? The running port may defer if something is already running on the default port of create-react-app.
create-react-app is a React toolchain, which packages some useful tools together to let you dive into development without any initial setup. Local development server is a part of that toolchain, it's only purpose is to serve static files your react app needs.
Sure, create-react-app lets you configure some options with environment variables but it is not meant to serve as backend for your react application.
You can achieve this with your own backend by writing an endpoint to get the server port but for the local server I don't think it is possible.
This functionality is not available since React App and Local server are running independently.
However, your server port will be available when you start the server. So you can have another API that will simply fetch the port of the server and that can be displayed accordingly.
Something like this on the server.
app.get('/server/port', (req, res) => {
return res.json({port: server.address().port})
})
where your server is started at
const server = app.listen(20000)
In the react app, you can have the fetch request like this
fetch('http://localhost:20000/server/port')
.then(response => response.json())
.then(data => console.log(data));
// you will have the port no. in data.port
This will be helpful to you.

Proxy in production React for fetch API express

I was developping a app with React app. In developing env i was using proxy but I'm deploying the app and I saw that proxy didn't work in.
I read about http-proxy-middleware. It can be a solution or it don't works too?
Any way to do this without config the server with redirects to other port?
I need to continue fetching to my API server.
The best way what I found without configure server and NGINX is follow this steps:
Build front
Move folder into a backend server.
Put that code after routes:
if (process.env.NODE_ENV === 'production') {
app.use(express.static(`${__dirname}/yourFrontFolder/build`));
app.get('*', (req, res) => {
res.sendFile(`${__dirname}/yourFrontFolder/build/index.html`);
})
...
And build your backend code and access to your backend port like frontend.
You don't usually need a proxy in your React app when it is deployed. To deploy, you usually run npm run build, which creates a build directory containing all the compiled JavaScript and HTML files you need for the deployment. These are then served by a web server, such as NGINX or by your backend application.

Communication with an http-server

I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.
I run the site with http-server CLI command and navigate to localhost to access it from the browser.
How can I send data to the server side so the server side will save the data as a file?
I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.
The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server
PS: I have to run this with http-server, this is an offline project.
You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.
You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.
You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.
For examples on how to serve static content in your own backend see:
How to serve an image using nodejs
You should use express for this kind of stuff. You can easily make methods that handle certain requests.
Here is an exmaple on how to handle a get request by just sending some data
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
And you can use the fs api from node itself to write data.
var fs = require('fs')
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
Note: the fs example uses arrow functions. You can find more information here

Categories

Resources