Connect express backend to React frontend (in the same server if possible) - node.js

I saw a lot of ways to connect React frontend to express backend (REST API) and i don't understand which one of the them is the most common, organized and friendly. (Axios, componentDidMount function and so on..).
My project divide to backend and frontend libraries which includes a connection to mongoDB in the backend.
I am new to React so i will appreciate any recommendation.

You can easily have both on the same server, all you need to do is. Make an express route that servers your react app's index.html.
app.get('/', (req, res) => {
res.sendFile('./public/index.html');
});
Also, don't forget to serve your static files (css, fonts, etc) using express's own middleware.
app.use(express.static('public'));
After you have done that, you can have your API at /api.

Related

Separate Node and React App: Allow Express passthrough to React Router

I have two separate apps: one of them is my API in Node with Express, and the other is my front end in React with React Router.
Typically when doing smaller apps, you might have the server code colocated with your client code in the same repo, but in this case they are separate repos. I am trying to allow passthrough to React Router from Express if the route is not matched, and we traditionally do it like this:
app.get('*', function(req, res) {
res.sendFile(path.resolve(__dirname + 'dist/index.html'));
});
See the problem? I don't have the dist folder on my server, so I have no reference to the index.html available. The reason I broke out the repos is because I upload all the front end code to a CDN, and can just proxy the network requests to my API.
How do I allow the passthrough from Express to React Router if I don't have a file or path to resolve in the res.sendFile catch-all ?
A bit of a hack, but I realized that this would probably work and I tried it out and it does indeed. You can probably take this a step further and even extract the referrer from req.headers.
request("https://yourwebsite.com/index.html",(error, response, body) => {
res.send(body)
}

Express and React js: deal with api request, proxy?

My situation:
I'm using Express and passport.js as my backend API server and React js as my front-end.
What I'm currently facing is that I keep getting index.html file when I request my passport auth by "/api/auth/*". However, it works as I expected when I'm making a request from my front-end via proxy.
So I tried using Regex to exclude "/api/*" route from using static build files.
app.use('/api', api)
app.use(/^\/(?!api).*/, express.static(path.join(__dirname, '/../build')))
app.get(/^\/(?!api).*/, (req, res) => {
res.sendFile(path.join(__dirname, '/../build/index.html'))
})
But not like my expectation, I just got Unexpected token < warning ...
How can I get my get "/api" route to work also while using React js build files?
Or should I just keep making a proxy request from React js dev server?
I want to understand how Express and React js app deployed in some server work together.

Angularjs4 with express generator

Just developed a simple angular 4 application with this tutorial
https://scotch.io/tutorials/mean-app-with-angular-2-and-the-angular-cli
But how can i integrate angular 4 app to a express application that generated with express generator??.
One approach is REST API's method that is express JS app use as API provider and the angular application communicate with REST api.
But i would like to serve the angular application from express application itself..
I think this will helpful to you. First I assume, you use express server to handle some api request and let's say those routes are begin with /api. they can be differ from yours.
First build your angular application by ng build and it will create a folder called /dist in your project folder.
Copy that folder in to your express project /public folder. You have to put them in an static routed folder. /public folder is a default static route folder. That is why I put it there. If you have your own one, you can put there too.
edit your app.js file as follows
// Set our api routes
app.use('/api', api); // API router definitions.
// Catch all other routes and return the index file
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
Hope you will help this way. Thanks.
You can serve it through your server like this:
// Catch root route and return index.html
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'app/index.html'));
});
// Catch all other routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'app', req.originalUrl));
});
But be careful to set the right path to your index.html.
There is a technology stack called MEAN which means (coincidence :) MongoDB, Express, Angular and Nodejs. So this is basically what you are looking for.
Altough you can create you own file structure, there is a mean-cli similar to Express-generator and the angular-cli. You can find it here.
In order for Angular to work properly (like requesting a site like example.com/something and then also activate the route something) I always return my index.html for any request and setup express to return all static files as well. Then I create a route /api which handles all my REST api requests.
Make sure to first setup your /api route, then your other static files from angular like bundle.js and finally index.html as route **.

Angular in a NodeJs Server

I'm beginner in Angular. I have a nodejs server and I have Angular for the front end. Now I would like to know if it's possible to have just one server for both ?
Because in some videos from youtube, they had one server for node and one server for angular.
Thank you, bye
At a basic level you'd need to set the static path for your built, static Angular files and if you are using Angular routing you'd probably want to direct all requests to your index.html of the Angular project so that Angular can handle all client side routing.
For example, setting the static path for a built Angular CLI project that sits in the default public folder created by express-generator. The example uses dist as that is the default destination of the Angular CLI project when you execute ng build.
app.use(express.static(path.join(__dirname, 'public', 'dist')));
Catch-all route to direct any requests not caught by your Express application route definitions, such as RESTful routes returning JSON data or similar, to the Angular project's index.html:
// some routes
var users = require('./routes/users');
app.use('/users', users);
// other routes
var todos = require('./routes/todos');
app.use('/todos', todos);
// catch-all route
// needs to go AFTER all other express server route definitions
app.use('*', (req, res) => res.sendFile(path.join(__dirname, 'public', 'dist', 'index.html')));
If using Angular CLI, during development you can run the projects separately, using a proxy.
Hopefully that helps!
Yes, it's possible to have one server for both.
You can serve your AngularJS files via your favourite HTTP server (e.g. express) on your NodeJS server as static files like so:
app.use(express.static(path.join(__dirname, 'client')))
Where client is the directory containing your front-end content.

create-react-app with Express

I need to query a database and I'm using create-react-app. The library to connect to the DB (pg-promise) does not work with Webpack and needs to be running on a Node server.
So I installed Express and have this:
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
})
How can I load data from the database from the React pages? I though of using request but how can I make a request to my own server? And what should I add to the lines of code above? I think it would be something like:
app.get('/query/:querybody', (req, res) => {
// process and return query
})
Is this right? How can I make it work with a SPA?
Probably the most friction-free method would be to have a separate app.js or server.js along side your CRA application. You can use a tool like concurrently to run both your React app and the express app.
The trick is to serve your express app on a different port than the default :8080 that CRA serves on. Usually 8081 is a good choice, as it's a common convention to use port numbers that are close together when developing.
In your React app, you will need to make sure you use the full URL for the express endpoint: http://localhost:8081/query/...
On the server side you are going in the correct direction: you need to setup endpoint which will respond with data based on request. In you example you setup an endpoint for a GET HTTP request. If you will need to pass a complex request (for example add new record to database), consider using POST HTTP requests.
On the client side (in the browser) you will need a library that will assist you in sending requests to your server. I can recommend to try Axios (https://github.com/mzabriskie/axios). Usually if you omit protocol, server name and port, request will be sent to the server from which the page was loaded:
http:127.0.0.1:8001/api/endpoint => /api/endpoint

Resources