Wednesday, 31 May 2017

Electron - ECONNREFUSED on all outgoing (xhr) requests in the web app - but the server's up and CORS is enabled.

I'm wrapping a web application inside an Electron app. The web application tries to connect to a remote server - which is publicly accessible and CORS is enabled. I can access the server fine using the browser, and running the web app in a browser also works. However, after wrapping it in the Electron app, it all fails.

The electron app runs a local webserver (express), which hosts the files. The files are then loaded into the BrowserWindow. Code's below. In the screenshot, you can see the type of error I'm getting. The server is accessible at http://demo.signalk.org

Any ideas? The webapp uses superagent to make the actual request.

An image of the error

The code:

const electron = require('electron')
const express = require('express')
const join = require('path').join
const url = require('url')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let server = null
let mainScreen = null
let mainWindow = null

app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')

function initServer() {
  if (server !== null) {
    return
  }

  const path = join(__dirname, '../www')
  console.log('static path', path)

  server = express()
  server.use('/', express.static(path))
  server.listen(33013, '127.0.0.1')
}

function createWindow() {
  if (mainWindow !== null) {
    return
  }

  initServer()
  mainScreen = electron.screen.getPrimaryDisplay()

  mainWindow = new BrowserWindow({
    height: mainScreen.workAreaSize.height,
    width: 450,
    show: false,
    icon: join(__dirname, '../../resources/Icon.png'),
  })

  mainWindow.loadURL('http://127.0.0.1:33013')

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
    mainScreen = null
    server = null
  })
}

app.on('ready', () => {
  createWindow()
})

app.on('window-all-closed', () => {
  if (process.platform === 'darwin') {
    return
  }

  app.quit()
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

module.exports = {
  app,
  mainWindow,
}



via Fabian Tollenaar

No comments:

Post a Comment