works well with command "elctron ." but doen't when i bulit and execute

28 views Asked by At

app works well when i run "electron ." but doesn't work when i run the app that i built through electron-forge

The app works like below

  1. make a webserver that get data from mongodb when requested
  2. use fetch function in JS file that linked with script tag into html file

Codes are like below

app.js : main electron JS file

require("./server")();

const { app, BrowserWindow } = require('electron');


const createWindow = () => {

    const win = new BrowserWindow({
      width: 1300,
      height: 860,
      devTools: true,
    })
  
    win.loadFile("./home.html");
}

app.whenReady().then(() => {
    createWindow();
});

server.js : express web server

module.exports = ()=>{
    const PORT = 22410;
    const db = require("./db")();
    const express = require("express");
    const server = express();

    server.use(express.json());

    server.get("/getAll", async (req, res)=>{
        let query = req.query.q;
        if(query) query = JSON.parse(query);
        const data = await db.getAll(query);
        console.log(data);
        res.send(data);
    });

    server.listen(PORT, ()=>{
        console.log("server -ing");
    });
};

db.js : get data from mongoDB

module.exports = ()=>{
    const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
    require("dotenv").config();
    const {CONNECTION_STRING, DB_NAME, COLLECTION_NAME} = process.env;

    const makeConnection = ()=>{
        const client = new MongoClient(CONNECTION_STRING, {
            serverApi: {
                version: ServerApiVersion.v1,
                strict: true,
                deprecationErrors: true,
            }
        });
        const db = client.db(DB_NAME);
        const collection = db.collection(COLLECTION_NAME);

        return {client, collection};
    }

    return {
        getAll : async (query)=>{
            const {client, collection} = makeConnection();
            try {
                const result = await collection.find(query);
                const parsedResult = await result.toArray();
                return parsedResult;
            } catch (error) {
                console.group();
                console.log("ERR : db.getAll()");
                console.log(error);
                console.groupEnd();
                return error;
            } finally {
                await client.close();
            }
        },
    };
}

home.js : JS linked with 'home.html'

fetch("http://localhost:22410/getAll")
.then((res)=>{
    return res.json();
}).then((results)=>{
    .... //doing something
    });
});

I checked that i can get response from server itself, but it seems like 'db.js' section doesnt work well.

0

There are 0 answers