Is it possible to directly connect ReactJs with ExpressJs? - node.js

My needs are simple, I want the ReactJs frontend served from an ExpressJs server, without crazy separate ports and stuff.
Is it possible to send HTTP requests to my server for APIs as well?
How can I do this?

Yes and yes.
You create the react site. Use the dev server to develope it and make it look nice. When its ready you build it by doing
npm run build
Then you create the express server and make it serve the static html files
const express = require('express')
const app = express()
app.use('/', express.static('dist'))
app.listen(3000, () => { console.log('running on 3000') })
Now you can open the express app on server 3000 and it serves the react site.

Related

React app (via create-react-app) with Express backend in single Azure app?

I have a React front-end app with an express backend that's working locally as a proxy API server.
In my local dev environment, the React fonr-end is running on port 3001, with the Express server running on port 3000.
In my package.json, I have the proxy set up:
"proxy": "http://localhost:3000",...
The app is deployed via an Azure pipeline, which builds the app and the server, zips them up, and copies the artefacts to an Azure domain.
In the Azure app's Configuration, I have the following Startup Command:
node server & npx serve -s
This should (in theory) start the Express server (which is set to listen on port 3000) and server the front-end. The front-end is indeed accessible, but when it tries to make a call to the api via a simple fetch request, it's returning the HTML of the React app instead of a JSON response. This indicates to me that it's not actually exposing the Express port to the front end.
Is it actually possible to server the Express server and the frontend as part of the same container?
It turns out that this approach - while it was the wrong one - was in fact working, but Azure App Services will only expose a single port. In this case, we could either expose the React front end via npx serve -s OR expose the api by setting the PORT variable to 3000. Both were running, but only one could be reachable.
The solution was to serve the React front-end via the Express server:
const path = require('path');
const { response } = require('express');
const express = require('express');
const request = require('request');
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, '../')));
app.use('/api', function (req, res, next) {
// API function calls here
...
});
app.get('*', function(req, res, next) {
res.sendFile(path.join(__dirname, '../index.html'));
});
app.set('port', 3000);
app.listen(app.get('port'), () => {
console.log('Proxy server listening on port ' + app.get('port'));
});
And set the PORT container variable to 3000.

express.js cannot find route at reload after initial load

I created a small express server to serve my react app. It's a static context react app that only uses API calls to fetch and show data.
When I start my server everything goes well and when I navigate to localhost:5000 the server automatically redirects to localhost:5000/login. However, the server throws an error once the login page is loaded and I trigger a reload. It then gives me Error: Cannot GET /login.
Does anyone has an idea what goes wrong? Here is the code of my express server script which I trigger with yarn start (added start script in package.json ("start": "NODE_ENVIRONMENT=production node server.js").
const express = require("express");
const app = express(); // create express app
// add middleware
app.use(express.static("dist"));
// start express server on port 5000
app.listen(5000, () => {
console.log("server started on port 5000");
});

Use Reactjs app as a frontend for express nodejs in backend on domain

I created a frontend app using react js that calls an express node js api in the backend, in localhost i don't have problems because it runs on localhost, but when i deploy them both on plesk server, i don't know how to call express api from my react js app.
1.How to run express node js in production on plesk server.
2.How to call express api from react js app (in localhost i use http://localhost:8000/users)
Thank you kindly
This deployments assumes, you build your react app into your express app. So in final, your app runs on the same domain as your backend.
E.g. if you build your react app to reactapp folder within your express, then you serve it with:
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'reactapp/index.html'));
});
And on the same express you have another route for your api:
app.get('/api/somerestapi', (req, res) => {
// process your api request
res.send({data: 'some data'});
});
It means, you call your API from React with relative path:
const request = new XMLHttpRequest();
request.open('GET', '/api/somerestapi);
...

Run backend directly in Angular ng serve

I'm currently developing using ng serve, with proxy configuration, while the proxy points to another nodejs instance on the same machine.
This backend is a simple express server, like this (simplified):
var express = require('express');
var app = express();
var customers = require('./customers.controller.js');
app.get('/api/customers', customers.getAll)
var server = app.listen(8081)
The frontend (ng serve) runs on port 4200 and proxies /api to http://localhost:8081/api
As far as I can see, this is the recommended setup.
However, I would prefer to have the backend running directly inside of ng serve instance instead of the proxy.
And if possible, even take advantage of the automatic reload feature of ng so that I don't have to restart the server if I change something on the backend code.
As both are nodejs and ng seems to be configurable, I think this is possible, but I can't find a starting point for defining my own routes
Its possible to do this
you just need to put your angular into the backend by utilize the nodejs routing
basicly angular is a "static file" and the entry point is coming from the index.html
// Redirect all the other resquests
this.app.get('*', (req, res) => {
res.sendFile(path.resolve('dist/index.html'));
});
but remember you need to handle the routing for image, js, css and others also.

Using Mixpanel - Node Library in Express

I am currently trying integrate the Mixpanel Node library into a test application that I am building. This is a Node.js application using the express framework.
As per the express docs, I have a JS file to manage the project, a folder called "public" that contains all of my static files, and another folder with the node modules that come with express.
I have two static HTML pages in "public" that I am trying to put mixpanel tracking into. I am running the project locally by running node app.js.
app.js includes:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
//Mixpanel Additions
var Mixpanel = require('mixpanel');
var mixpanel = Mixpanel.init('<I am putting my project token here>', {
protocol: 'https'
});
//App Configuration and Init
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/public/page.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
In my HTML files I try to use mixpanel functions by putting them into script tags:
<script>
mixpanel.track("event")
</script>
But when I run node app.js and view the page in my browser it says:
Uncaught ReferenceError: mixpanel is not defined
I have a pretty poor understanding of node.js, but I am imagining that I need to use app.use(), app.get(), or something along those lines to get the Mixpanel lib loaded into the app. What am I doing wrong? I also realize that my understanding of Express and Node is pretty rudimentary, so any additional knowledge is appreciated, especially if I am way off.
If you want to call mixpanel tracking functions in the browser, you should load the mixpanel library in a script tag on the browser side, as seen here:
https://developer.mixpanel.com/docs/javascript
The purpose of the node.js package is to send events from the server side, like if you wanted to log when page.html is rendered, you could do
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/public/page.html'));
mixpanel.track('event')
});

Resources