YourGoodFriend
YourGoodFriend

Reputation: 973

Client http request to an Electron app

So I am working on a project that I would like to turn into an electron app, currently it is an Angular (2.x) app and using express as the server.

The issue I am running into is how to replicate the express router in electron? Basically I want to be able to do gets, posts, updates etc from the client down to the electron server (currently using @Angular/http service). I know electron has their own message protocol for asynchronous/synchronous messages but it is more akin to a web socket.

Client side example:

this.http.post('/setValue', {key: key, value: value}).subscribe((data)=>{});

Server side:

router.post('/setValue', (req, res, next)=>{
    //Do something
});

Upvotes: 1

Views: 4602

Answers (2)

Sergio Lissner
Sergio Lissner

Reputation: 75

Insert the following code in your main.js, customize end-point depending on your requirements.

const http = require('http');

const port = 8889;

try {
  const hostname = 'localhost';
// Creating Server
  console.log(`Start preparing a Server for starting at http://${hostname}:${port}/`);
  const server = http.createServer((req,res)=>{
    // Handling Request and Response
    res.statusCode=200;
    res.setHeader('Content-Type', 'text/plain')
    res.end("Front-end is alive.")
  });

// Making the server to listen to required hostname and port number
  server.listen(port, hostname,()=>{
    // Callback
    console.log(`Server is running at http://${hostname}:${port}/`);
  });
} catch(e) {
  console.log(e);
}

Upvotes: 0

Dennis W
Dennis W

Reputation: 961

You should be able to start an express server in your Electron startup script. Just have it listen on some random port number and have your Angular2 app hit http://localhost:port URL for all of its http requests.

My advice would be to split the original Angular2 app into two separate apps:

  1. Keep your express routes the way they are, and move them into their own dedicated API. Host the API somewhere and give it its own URL.

  2. Have the Electron app hit the API URL for all database related calls.

This would give you separation of concerns and make the system easier to manage. In addition, your API would be available for other apps to use in the future. For instance, let's say you have to do a mobile app next, the mobile app could take advantage of the existing API and you save yourself a lot of work.

Upvotes: 2

Related Questions