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)
Related
I have a React TS browser app with Azure Functions back end that I am trying to implement WebSockets in using Azure Web PubSub.
Following the guide at https://learn.microsoft.com/en-us/azure/azure-web-pubsub/tutorial-serverless-notification?tabs=csharp I can get the Azure Functions to Web PubSub side working, but in the example the client page is within the Azure Functions app. The following code snippets are from the guide.
Azure Function for negotiating PubSub connection and getting access token:
[FunctionName("negotiate")]
public static WebPubSubConnection Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
[WebPubSubConnection(Hub = "notification")] WebPubSubConnection connection,
ILogger log)
{
log.LogInformation("Connecting...");
return connection;
}
Simple client page:
<html>
<body>
<h1>Azure Web PubSub Notification</h1>
<div id="messages"></div>
<script>
(async function () {
let messages = document.querySelector('#messages');
let res = await fetch(`${window.location.origin}/api/negotiate`);
let url = await res.json();
let ws = new WebSocket(url.url);
ws.onopen = () => console.log('connected');
ws.onmessage = event => {
let m = document.createElement('p');
m.innerText = event.data;
messages.appendChild(m);
};
})();
</script>
</body>
</html>
I run this locally on http://localhost:7071 and can successfully negotiate, connect to the WS, and display messages.
If I try and connect my React front end app (http://localhost:3000), I can still hit the negotiate function in my function app, but then get a CORS error when trying to connect to the WS.
Presumably I could handle the negotiate within the React app, but that would mean storing the Azure PubSub access token in React. Any better way to do this?
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 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.
I am using http-proxy-middleware in my reactApp.
Backend is implemented in Springboot .
Springboot Webflux is being used to send the Flux data to UI .
When I am directly using
eventSource.onmessage = (event) => {
console.log(event);
};
I am able to see the messages.
But when I am using
const apiURL = "/test"
eventSource = new EventSource(apiURL);
Then I am not able to see the messages.
my setupProxy.js includes
const proxied =
pathname.match("^/test") ;
return proxied;
};
module.exports = function (app) {
app.use([
createProxyMiddleware(apiFilter, { target: apiUrlTest, ws: true }),
]);
};
Is there any way to resolve it. Why on direct call i m getting messages but when calling through proxy I am not able to view the message.
I have NodeJS server + AnglarJS page.
All works.
Do working examples or frameworks that allow the download page on the server NodeJS and fill it and return to the client a static page. It is necessary for Browsers IE 5-8 (90% clients).
Yes, take a look at Express for Node.js - you can easily serve up a single static page and then use a link to redirect users to your Angular app (using a 'login' page, for example).
Here is an example of a very basic Express app.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
The req (request) and res (response) are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback) and anything else you would do without Express involved.
The app starts a server and listens on port 3000 for connection. It will respond with "Hello World!" for requests to the homepage. For every other path, it will respond with a 404 Not Found.
Save the code in a file named app.js and run it with the following command.
$ node app.js
Then, load http://localhost:3000/ in a browser to see the output.