React App and Express Server routing for a single page application - reactjs

How do I set the routes for my React Single page application in Express js
Navigate a React App link from a single page application to Express server dynamically

Your question is not completely clear but I'm assuming you want to know how to use express for API routes and still server react on the frontend. If this is the case you can do it like this on your backend file (let's call it server.js). And the react app is in a folder called "client":
const app = express();
// API routes
app.get("/api/test", (req, res) => {
res.send('example response from backend');
});
// If no API routes are hit, send the React app
app.use(function (req: Request, res: Response) {
res.sendFile(join(__dirname, "./client/build/index.html"));
});
Note that you have to send the React app last. This line must come after all other routes.

Related

React axios - calling a http endpoint from https webapp

am trying to call a http endpoint from my react web application created using create react app
i am given the below code and a local pem file
caCrt = fs.readFileSync('./ca-crt.pem')
const httpsAgent = new https.Agent({ ca: caCrt , keepAlive: false })
axios.get(url, { params: params, httpsAgent: httpsAgent {color:#0747a6}}) .then( res =>
not sure how i can call it properly from frontend (https web app), i received several "mixed content" error from chrome, understand that i may not be able to use "fs" module from my react app

How to server-side render a specific route in ReactJS?

I would like to server-side render only a specific route in React. For example, /home should be client-side rendered, but /post should be server-side rendered.
The /post route receives a post ID as a parameter(using react-router) and fetches the content from a database server.
Is their any way I can server-side render only a specific page/route using react-dom server?
Your data should be handled by the middleware and stored there to minimize api calls. The Front end should render based on that data.
One good approach is to use built version of your react within express.js server. So let's say you have your built version of your react inside build directory :
var express = require('express');
var app = express();
app.use("/post",function(req,res) {
console.log(req); // Do your stuff for post route
});
app.use("/",express.static(path.join(__dirname,"/build")));
app.use("/*",express.static(path.join(__dirname,"/build"))); // Handle react-router
const httpServer = require("http").createServer(app);
httpServer.listen(8080, function(){
console.log("Server is running on 8080");
});

How could I trigger an Electron api from an external server?

new to Electron development and I here's the idea I'm trying to implement:
I want to make a request to an express server from a website that's not my electron app with a payload of data and for that express route to respond by focusing the electron browser window and sending the electron app the request payload for it to display.
Currently have an Electron app using loadFile to render an html.index which loads a bundled React application. I know you can use ipcMain/ipcRenderer to talk between the main electron process and the react app renderer process, but I don't know how I would go about having my express app talking to electron.
Also not sure about how I would send the request payload to the electron application from the express route. Would I need to create a websocket or event emitter of some kind for the renderer process (the react app) to receive messages directly from the server?
tldr: I want to call browserWindow.focus() from an express route and then send the req payload to the front end application for display
You can do this with websockets/socket.io.
using socket.io, essentially you’ll just have a socket emission in the callback of your http request.
here's a small example:
in your express application, setup a socket.io server with a route that emits a focus-window event:
const app = require('express')()
const http = require('http').createServer(app)
const io = require('socket.io')(http)
app.post('/focus-window, (req, res) => {
io.emit('focus-window')
res.send(200)
});
io.on('connection', (socket) => {
// connections here
console.log('a user connected');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
in your electron main process, setup a socket client using socket.io-client that has access to the BrowserWindow object like this:
const { app, BrowserWindow } = require('electron')
const socket = require('socket.io-client')('http://localhost:3000')
const path = require('path')
function createWindow () {
// Create the browser window.
const win = new BrowserWindow({
width: 400,
height: 600
})
// and load the index.html of the app.
win.loadFile(path.resolve('dist/index.html'))
// setup your socket listeners
socket.on('connect', function(){
console.log('socket.io-client connected')
})
// here it is listening for the focus-window event
socket.on('focus-window', () => {
win.focus()
})
}
app.whenReady().then(createWindow)
you can then use the socket emitter to send info to the electron app and then use electron's ipc to send the information to the react renderer process (conceptually, I haven't tested this)

Host react app and laravel backend(Admin panel) in same laravel application project

I want to host the react app and laravel app in the same laravel application project.
The front end app is react and backend(admin panel) laravel.
I want redirect all request to specific front end view except first URL segment == backend/:any
Eg.
http://host.com/backend/(any)
Continue with laravel router
http://host.com/(any) except backend/
Continue with react router
Any idea for that matter?
You have two options here, either pass a regular expression to the any route to ignore API prefixed routes
Route::get('/{any}', function () {
return view('index.blade.php');
})->where('any', '^(?!backend).*$');
Route::fallback(function () {
return view('index.blade.php');
});
From the docs
Fallback Routes
Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Typically, unhandled requests will automatically render a "404" page via your application's exception handler. However, since you may define the fallback route within your routes/web.php file, all middleware in the web middleware group will apply to the route. You are free to add additional middleware to this route as needed:
Route::fallback(function () {
//
});
The fallback route should always be the last route registered by your application.
Try something like this in the "routes/web.php":
// WRITE BACK-END ROUTES AT FIRST
Route::group([
'prefix' => 'backend',
], function () {
Route::get('/', 'AdminController#dashboard')->name('dashboard');
Route::get('admin-page-1', 'AdminController#page1')->name('page1');
Route::get('admin-page-2', 'AdminController#page2')->name('page2');
// some other admin routes if you need
});
// FRONT ROUTE(S)
Route::get('/{text}', 'FrontController#front')->name('front');

routing of static website using nodeJs

I build a website using angular js. But That is not a SPA. I use angular js for API calling and fetch some data only so now I want to do routing for custom URL of my HTML pages how will I do it ? I am serving my website using nodeJs. is there any configuration in node js to set custom URL of static website/routing.
For using the routes in nodejs you can use express.Router() module.It can be installed same as express and then you can define the routes on that.
For example :-
var adminRouter = express.Router();
adminRouter.get('/',function(req,res){
res.send('Here is the dashboard for my app');
});
adminRouter.get('/users',function(req,res){
res.send('Here is the menu to show all the users');
});
//Now to apply the routes to your app
app.use('/admin',adminRouter);
You can also route the middleware of your app and the url parameters separately

Resources