Client using websocket to not connecting

My client just shows the status as closed. My C# application is using websocket-sharp:

WebSocketServer mWebSocketServer;

try {
  // Creation of server, ipWebSocketAddr = "ws://192.168.5.73/posttest.html
  // mcintWebSocketPort = 443
  mWebSocketServer = new WebSocketServer(ipWebSocketAddr, mcintWebSocketPort);
  mWebSocketServer.AddWebSocketService<clsQuintexMsg>("/clsQuintexMsg");
} 
catch (Exception ex)  
{
  FrmMain.UpdateTaskbar(ex.ToString());
}

In my JavaScript:

try {
  webSocket = new WebSocket(cstrServerSocketIP);
  
  //Setup timeout timer to timeout if webSocket does not connect
  tmrCheckWebSocket = setInterval(function() {
    var strMsg = "Checking webSocket (" + cstrServerSocketIP + "), ";
    if (typeof webSocket == "object" &&
      typeof webSocket.readyState == "number") {
      if (webSocket.readyState == WebSocket.CONNECTING) {
        strMsg += "connecting";
      } else if (webSocket.readyState == WebSocket.OPEN) {
        strMsg += "open (connected)";
      } else if (webSocket.readyState == WebSocket.CLOSING) {
        strMsg += "closing";
      } else if (webSocket.readyState == WebSocket.CLOSED) {
        strMsg += "closed";
      }
    } else {
      strMsg += "not a valid websocket!";
    }
    DebugMsg(strMsg);
  }, cintCheckWebSocketInterval);
  
  webSocket.onclose = (event) => {
    var strReason = "";
    if (typeof event == "object") {
      if (typeof event.code == "number") {
        strReason += "code[" + event.code + "]";
        var strError = cobjWebSocketErrors[event.code];
        if (typeof strError == "string") {
          strReason += ":" + strError;
        }
      }
      if (typeof event.reason == "string" && event.reason.length > 0) {
        if (strReason.length > 0) {
          strReason += ", ";
        }
        strReason += "reason:"" + event.reason + """;
      }
    }
    DebugMsg("webSocket.onclose " + strReason);
  };
  
  webSocket.onerror = (event) => {
    DebugMsg("webSocket.onerror" + ((typeof event == "object" && typeof event.data != "undefined") ? ":" + String(event.data) : ""));
  };
  
  webSocket.onmessage = (event) => {
    DebugMsg("webSocket.onmessage");
    if (event.data instanceof ArrayBuffer) {
      console.lob("Received ArrayBuffer");
      console.lob(event.data);
    }
    webSocket.close();
  };
  
  webSocket.onopen = () => {
    DebugMsg("webSocket.onopen");
  };
  
  //Set-up timer to send requests for data updates
  InstallServiceTimer(cintServiceRequestInterval);
} catch (e) {
  DebugMsg(e);
}

Just found an exception is being thrown in c# application when calling start:

System.InvalidOperationException
  HResult=0x80131509
  Message=There is no server certificate for secure connection.
  Source=websocket-sharp
  StackTrace:
   at WebSocketSharp.Server.WebSocketServer.start()
   at WebSocketSharp.Server.WebSocketServer.Start()
   at CheetahCS.clsServer..ctor(String strRoot, String strDefault, Int32 intWWWPort, Int32 intWebSocketPort) in clsServer.cs:line 131

  This exception was originally thrown at this call stack:
    WebSocketSharp.Server.WebSocketServer.start()
    WebSocketSharp.Server.WebSocketServer.Start()
    clsServer.clsServer(string, string, int, int) in clsServer.cs

Why does it think this is a secure connection?

DevExpress SpellChecker – ASP .NET Core

I am having this next issue as regards the spellchecker I am trying to set up. The target platform for running my application is .Net Framework 4.8

First of all, I followed the Spellcheck chapter from the ASP.NET CORE controls documentation. The rest of the DevExpress Rich Editor works perfectly, does what it has to do.

To give more detail, in order to set up the spellchecker, you have to Create a nspell Bundle for the RichEdit which is is a built that is done through npm.

1: Run the following commands within the root directory:

console
npm i [email protected] --save-dev
npm i [email protected] --save-dev
npm i [email protected] --save-dev
npm i [email protected] --save-dev

If you need the corresponding dictionaries, you have to go to this certain page and download them.
https://github.com/wooorm/dictionaries

  1. Add the import directive for every additional dictionary to the node_modules/devexpress-richedit/bin/nspell-index.js file. Did that.

  2. Register additional dictionaries with a corresponding “lang” attribute prior to the default English dictionary to use them first while spell checking.

import enAff from 'dictionary-en/index.aff';
import enDic from 'dictionary-en/index.dic';
    
import esAff from 'dictionary-es/index.aff';
import esDic from 'dictionary-es/index.dic';
    
export const nspell = nspellImport;
export const dictionaries = [
  { lang: 'es', aff: esAff, dic: esDic },
  { lang: 'en', aff: enAff, dic: enDic },
];
  1. Run the following command that builds an nspell bundle according to the node_modules/devexpress-richedit/bin/nspell.webpack.config.js configuration file:
npx webpack --mode production --config=node_modules/devexpress-richedit/bin/nspell.webpack.config.js

I ran it and the command creates the node_modules/devexpress-richedit/dist/custom/nspell.js file. A script in the file appends the nspell object to the JavaScript window object.

I have concisely followed these 4 steps and then had to do this next series of actions:

  1. Create the spell-checker-worker.js file with the following content: ( it’s inside the documentation I attached)

  2. Place the nspell.js and spell-checker-worker.js files into the directory that contains the control scripts (wwwroot for .NET Core, Scripts for MVC and Web Forms). In my case, I put it inside a folder located in Scripts/devexpress-richedit

  3. For an application on a client framework, add the following code to the page that contains the RichEdit control. In my case I added the code inside my loadOptionsToInitializeContainer function which is called in my main razor View Page.

  4. In order to confirm that what I did is working, I attached the function addWordToDictionary on the Ribbon tab by the name Add word to dictionary. The ribbon item is inserted correctly on the bar every time I click, it enters inside the function but it does absolutely nothing.
    To give a bit more in-depth explanation of the problem is that I track checkWordSpelling and addWordToDictionary functions in the handler which DevExpress possesses for the client-side. It’s this one. It is a handler that is added and at this point is tracking the command name of both functions that are included on initialization.

    richElementContainer.events.customCommandExecuted.addHandler(function (s, e) {
       switch (e.commandName) {
           case 'checkWordSpelling':
               var text = s.document.getText();
           break;
           case 'addWordToDictionary':
               console.log(s);
               console.log(e);
           break;
       }
    

    });

CODE:
JAVASCRIPT

function loadOptionsToInitializeContainer() {
    const options = DevExpress.RichEdit.createOptions();

    options.confirmOnLosingChanges.enabled = true;
    options.confirmOnLosingChanges.message = 'Are you sure you want to perform the action? All unsaved document data will be lost.';
    options.width = '1100px';
    options.height = '1100px';
    options.bookmarks.visibility = true;
    options.bookmarks.color = '#ff0000';
    options.fields.updateFieldsBeforePrint = true;
    options.fields.updateFieldsOnPaste = true;
    options.rangePermissions.showBrackets = true;
    options.rangePermissions.bracketsColor = 'red';
    options.rangePermissions.highlightRanges = false;
    options.rangePermissions.highlightColor = 'lightgreen';
    options.handled = false;

    //// spellchecker worker initialization
    var spellCheckerWorker = null;
    var spellCheckerCallbacks = Object.create(null);
    var spellCheckerWorkerCommandId = 0;

    options.spellCheck.checkWordSpelling = function (word, callback) {
        if (!spellCheckerWorker) {
            var myDictionary = JSON.parse(localStorage.getItem('myDictionary')) || [];
            spellCheckerWorker = new Worker('./spell-checker-worker.js');
            myDictionary.forEach(function (word) {
                spellCheckerWorker.postMessage({
                    command: 'addWord',
                    word: word,
                });
            });
            console.log(myDictionary);

            spellCheckerWorker.onmessage = function (e) {
                var savedCallback = spellCheckerCallbacks[e.data.id];
                delete spellCheckerCallbacks[e.data.id];
                savedCallback(e.data.isCorrect, e.data.suggestions);
            };
        }

        var currId = spellCheckerWorkerCommandId++;
        spellCheckerCallbacks[currId] = callback;
        spellCheckerWorker.postMessage({
            command: 'checkWord',
            word: word,
            id: currId,
        });
    };
    options.spellCheck.addWordToDictionary = function (word) {
        var myDictionary = JSON.parse(localStorage.getItem('myDictionary')) || [];
        myDictionary.push(word);
        localStorage.setItem('myDictionary', JSON.stringify(myDictionary));

        spellCheckerWorker.postMessage({
            command: 'addWord',
            word: word,
        });
    };

    var contextMenu = options.contextMenu;
    var reviewTab = new DevExpress.RichEdit.RibbonTab();

    var ribbonButton = new DevExpress.RichEdit.RibbonButtonItem("addWordToDictionary", "Add word to dictionary", { icon: "check", showText: true, beginGroup: true });
    reviewTab.insertItem(ribbonButton, 16);
    reviewTab.id = 16;
    reviewTab.localizationId = "Spellchecking tab";
    reviewTab.title = "Spellchecker";
    options.ribbon.insertTab(reviewTab, 16);
    var mailMergeTab = options.ribbon.getTab(DevExpress.RichEdit.RibbonTabType.MailMerge);
    options.ribbon.removeTab(mailMergeTab);
    var tab = options.ribbon.getTab(DevExpress.RichEdit.RibbonTabType.Insert);
    var mailMergeTab = options.ribbon.getTab(DevExpress.RichEdit.RibbonTabType.MailMerge);
    var tabHeadersFooters = options.ribbon.getTab(DevExpress.RichEdit.RibbonTabType.HeadersFooters);
    var fileTab = options.ribbon.getTab(DevExpress.RichEdit.RibbonTabType.File);
    var ribbonItemFooter = tab.getItem(DevExpress.RichEdit.InsertTabItemId.InsertFooter);
    var ribbonItemHeader = tab.getItem(DevExpress.RichEdit.InsertTabItemId.InsertHeader);
    var ribbonItemPageNumber = tab.getItem(DevExpress.RichEdit.InsertTabItemId.InsertPageNumberField);
    var ribbonItemHeadersFooters = tabHeadersFooters.getItem(DevExpress.RichEdit.HeaderAndFooterTabItemId.ClosePageHeaderFooter);

    // gets Home Tab
    var fileItemSave = fileTab.getItem(DevExpress.RichEdit.FileTabItemId.ExportDocument);

    // gets Save Option from Home Tab
    // Removes Save item from Home Tab
    fileTab.removeItem(fileItemSave);
    tab.removeItem(ribbonItemFooter);
    tab.removeItem(ribbonItemHeader);
    tabHeadersFooters.removeItem(ribbonItemHeadersFooters);

    var richElement = document.getElementById("rich-container");
    return [richElement, options];

}

RAZOR

In my razor View, I call the javascript function which I wrote for initializing the options for the container/rich-editor

  // this is that function which passes all options to a constant
  const containerPlusOptions = loadOptionsToInitializeContainer();

  // this is the container/rich-editor that is created from those options
      richElementContainer = window.richElementContainer = DevExpress.RichEdit.create(containerPlusOptions[0], containerPlusOptions[1]);
  window.completed = createRichEdit(window.modelRaw, window.inform);

What I really need to find is how to be able to set up the spellchecker correctly, I am at a certainly good path here but I have been stuck for some days now and don’t know what to try experimenting with. Thanks

form validation required attribute triggered before I submit my form in Reactjs

I have an form and with multiple TextFields from Mui , And i create a reusable Select box component for my project and I texted 2 code files

I have 2 text fields with required attribute In form , in form submission onSubmit function it goes to store at db and I set e.preventDefault();

So my problem is
If I directly go to click select Box it shows “Please fill in this field”
on fields but I didn’t even submit the form ,
It only happens when I click the select Box .
So now I completed the first required field of username and I have another one which is phone field so for now I leave phone field and goes to chose select Box and it shows “Please fill in this field” on phone field before submitting the form
But even it shows that , the select Box is opened and shows the option values ……Thank u in advance

Main File

const menuItems = ['val1', 'val2'];

function SavingDetails(e) {
    if (typeof (e) === 'string' && !e.target) { 
        // Handling case for select box returning value directly , like if chose value it returns value directly                                     o it doesnt have e.target , Like it returns val1 or val2 or none
        
return setUserDetails((prev) => ({
            ...prev,
            profession: e
        }));
    }
    const { name, value } = e.target;
    setUserDetails((prev) => ({
        ...prev,
        [name]: value
    }));
}

<div id="content-div">
<form>
    <label htmlFor="nameid">Name</label>
    <TextField 
        required 
        onChange={SavingDetails} 
        value={userDetails.username} 
        id="nameid" 
        name="username" 
        type="text" 
    />
</div>

<div id="content-div">
    <label htmlFor="num">Phone</label>
    <TextField 
        required 
        onChange={SavingDetails} 
        value={userDetails.userphone} 
        id="num" 
        name="userphone" 
        type="phone" 
    />
</form>
</div>

<SelectBox 
    onChange={SavingDetails} 
    selectBoxWidth="80%" 
    placeHolder="Choose"
>
    <MenuItem value="None">None</MenuItem>
    {menuItems.map((val, ind) => (
        <MenuItem value={val} key={ind}>{val}</MenuItem>
    ))}
</SelectBox>

Select Box and Menu item Re-usable component file jsx

import { useState, useRef, useEffect, Children, cloneElement, useCallback } from "react";

export function MenuItem({ value, children, onSelect, isSelected }) {
    return (
        <button
            type="button"
            value={value}
            onClick={() => onSelect(value)}
            className={isSelected ? 'active-dd-btn' : ''}
        >
            {children}
        </button>
    );
}

export function SelectBox({ placeHolder = 'Placeholder..', children, onChange }) {
    const selectRef = useRef(null);
    const [isOpen, setOpen] = useState(false);
    const [selectedValue, setSelectedValue] = useState("");

    const HandleChange = useCallback(
        (value) => {
            onChange(value);
            setSelectedValue(value);
            setOpen(false);
        },
        [onChange]
    );

    function openDropDown() {
        setOpen(!isOpen);
    }

    useEffect(() => {
        const handleClickAway = (event) => {
            if (selectRef.current && !selectRef.current.contains(event.target)) {
                setOpen(false);
            }
        };

        document.addEventListener("mousedown", handleClickAway);

        return () => {
            document.removeEventListener("mousedown", handleClickAway);
        };
    }, []);

    return (
        <div onChange={onChange} ref={selectRef}>
            <button onClick={openDropDown}>
                {selectedValue === undefined || selectedValue === '' ? placeHolder : selectedValue}
            </button>
            {isOpen && (
                <div id="dropdown">
                    {Children.map(children, (child) =>
                        cloneElement(child, {
                            onSelect: HandleChange,
                            isSelected: child.props.value === selectedValue
                        })
                    )}
                </div>
            )}
        </div>
    );
}

syntax error (Unexpected identifier ‘dict’) when trying to use qweb.render [closed]

With this code:

const { _t, qweb } = require('web.core');
const MyController = publicWidget.Widget.extend({

ajax.jsonRpc('/my/controller', 'POST', { 
  'id': $("#id").val(), 
}).then(function (data) {
  console.log($('#my_container')); // this returns the element correctly
  $('#my_container').append(qweb.render('my_template', { data: data }));
});

I’m getting this error message:

Error evaluating template: SyntaxError: Unexpected identifier ‘dict’

The error message is from the line calling qweb.render. What is the error with this code?

JS, Odoo15: a syntax error (Unexpected identifier ‘dict’) when trying to use qweb.render in odoo15e

With this code:

const { _t, qweb } = require('web.core');
const MyController = publicWidget.Widget.extend({

ajax.jsonRpc('/my/controller', 'POST', { 
  'id': $("#id").val(), 
}).then(function (data) {
  console.log($('#my_container')); // this returns the element correctly
  $('#my_container').append(qweb.render('my_template', { data: data }));
});

I’m getting this error message:

Error evaluating template: SyntaxError: Unexpected identifier ‘dict’

The error message is from the line calling qweb.render. What is the error with this code?

How do I remove a subGrid filter on deselect of the related subGrid record? I have managed to filter the related subGrid onRecordSelect of main grid

‘I have 2 subGrids on a form, the second of which filters based on record select of the first subGrid, however, on deselect of the record, the related subGrid filter remains. How do I remove this filter if the record is deselected? Mt code below for the filter:’

function subgridOnSelect(executionContext)
{
    var selected = executionContext.getFormContext().data.entity;
    var Id = selected.getId();
    formContext = window.ALLCONTEXT;
    
    if(Id != undefined && Id != null)
    {
        addSubgridEventListener(Id,formContext);
    }
    else
    {
        formContext.data.refresh();
    }
}

function addSubgridEventListener(recordid,formContext)
{
    var gridContext = formContext.getControl("subgrid_teamstemplatechannelfolders");
    //ensure that the subgrid is ready…if not wait and call this function again
    if (gridContext == null)
    {
        setTimeout(function () { addSubgridEventListener(recordid,formContext); }, 500);
        return;
    }
    //bind the event listener when the subgrid is ready

    var fetchxml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                    "  <entity name='sis_teamstemplatechannelfolder'>" +
                    "    <attribute name='sis_channelnameid' />" +
                    "    <attribute name='sis_foldermembergroupid' />" +
                    "    <attribute name='sis_foldername' />" +
                    "    <attribute name='sis_parentfolderid' />" +
                    "    <attribute name='sis_teamstemplatechannelfolderid' />" +
                    "    <order attribute='sis_foldername' descending='false' />" +
                    "    <filter type='and'>" +
                    "      <condition attribute='sis_channelnameid' operator='eq' value='"+recordid+"' uiname='Teams Template Channel Test 1' uitype='sis_teamstemplatechannel' />" +
                    "    </filter>" +
                    "  </entity>" +
                    "</fetch>";

    gridContext.setFilterXml(fetchxml);
    gridContext.refresh();
}
ALLCONTEXT;
function Onload(executionContext)
{
    ALLCONTEXT = executionContext.getFormContext();
}

I want to create a map similar to this with all the features ( filter, infobox…) [closed]

I am trying to create an interactive map for my website, similar to the one on https://kaessbohrer.com/fr/find-us
his map includes:

Interactive markers for multiple locations.
Pop-up details for each location when clicked.
Smooth zoom and pan functionality.
Integration into a modern web design.
From inspecting their page, it seems they may be using tools like Google Maps API or a JavaScript mapping library like Leaflet or Mapbox. However, I’m not sure about the best approach to replicate this functionality.

Could anyone guide me on:

What tools or libraries might be best to achieve this?
Any starter examples or tutorials for implementing such features?
How to manage dynamic data for locations (e.g., if the markers and details are coming from a database)?
I have experience with HTML, CSS, and JavaScript, but I’m relatively new to integrating interactive maps into a web page.

Any guidance or code snippets would be greatly appreciated!

How to distinguish chrome from chromium using javascript?

Problem:

Chrome has alternative methods for extensions’ installation, but chromium doesn’t. So for my product, which consist of web extension and some application on host machine, I need to show different instructions to user after installation. This instruction is opened in default browser so it’s one page with script inside, that create different page content for different browsers.

What I want:

I wanted to use userAgent to distinguish chrome from pure chromium, but now as I see, they both have the same userAgent and userAgentData. So is there any ways to find out if this is chrome or chromium?

Get .env file path in NestJS

I have a requirement to fetch the .env file path in nestjs and pass it to the ETLs that are executed from the backend application. my nestjs application is running on a linux machine as a service and the .env file location is passed into NestJS app using

EnvironmentFile=/path/to/env/file

How can I get this path in a variable in nestjs?

1 option is to have another variable in .env for ETL_CONFIG but it would be ideal if i can dynamically read the .env file path from within nestjs

Why does the GeoJSON format expect coordinates in an array rather than an object with keys?

Take the following example from their home page:

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  },
  "properties": {
    "name": "Dinagat Islands"
  }
}

The coordinates field expects longitude and latitude in the first and second indexes respectively of this array. This is confusing to me for the following reasons:

  • Longitude and latitude are not the same thing. Representing them in the same list seems illogical from a purely programming perspective however I understand that a list looks like traditional coordinates.
  • Human error is more likely with index-based variables in a list rather than accessing them through clearly labelled keys in an object. In fact, after briefly helping someone who is working with Leaflet, ArcGIS and GeoJSON, this exact thing happened. He accidentally swapped round the indexes for accessing longitude and latitude. Furthermore, one of the libraries expected the longitude and latitude to be the opposite way round, leading to further confusion. Even if the keys were differently arranged in an object, this same issue would not occur (unless you accessed the keys via indexes which is possible in some languages I suppose; but this is a bad practice that is generally avoided).
  • Regarding performance, in most contexts I expect GeoJSON to be processed in JavaScript via mapping libraries and the likes. Quickly looking at JavaScript arrays and objects, I can find both people claiming it is faster and slower, but either way, the performance difference seems to be not great enough to justify sacrificing semantics.

Is there any reason why this decision was made? What is the advantage of storing them in a list?

Specifications can be found here: https://datatracker.ietf.org/doc/html/rfc7946

Next.js 14.2.11 type error: s is undefined

This error is not permanent and only happens sometimes.

i have a multi step form, i call a action in last form and get this error in production (local project works).

also i use zustand for form steps global states, and add states to formdata in last form.

How to get a certain about of latest modified object?

I have thousands of images stored in my bucket. I use the ListObjectsV2Command to fetch images, it consistently retrieves only the 100 oldest ones. As the maximum limit for ListObjectsV2Command is 1,000 objects only, there doesn’t seem to be a way to fetch all objects and sort them effectively. Is there an alternative method to achieve this?

const client = new S3Client({ region: "us-east-1" });
console.log("Fetching images from S3");

const input = {
  Bucket: "mybucket",
  MaxKeys: 100,
};

const command = new ListObjectsV2Command(input);
const response = await client.send(command);

Unable to load preload script: Resources/app.asar/src/renderer.js

My preload is named renderer.js

I have an electron app that I compiled using Electron Builder, my app features numerous HTML pages, most of them get redirected from button clicks.

When I click a button to navigate to another html page, the same preload error is logged there and the app turns white. After closing devtools in that same state, it just becomes transparent, the app is still open but the HTML & CSS does not seem to be loading.

How do I configure the package.json so that the preload gets detected?

This is how my project looks like

// This is my main file, main.js

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1700,
        height: 810,
        minWidth: 1700,
        minHeight: 810,
        resizable: false,
        webPreferences: {
            preload: path.resolve(app.getAppPath(), 'renderer.js'),
            contextIsolation: true,
            enableRemoteModule: false,
            nodeIntegration: false,
            webSecurity: false
        },
        transparent: true,
        frame: false,
        backgroundColor: '#00000000',
    });
    mainWindow.loadFile(path.join(__dirname, 'Pages', 'index.html'));

    mainWindow.on('will-resize', (event) => {
        event.preventDefault();
    });
}
//preload.js

const { contextBridge, ipcRenderer, shell } = require('electron');

contextBridge.exposeInMainWorld('electronAPI', {
    send: (channel, data) => ipcRenderer.send(channel, data),
    on: (channel, func) => ipcRenderer.on(channel, (event, ...args) => func(...args)),
    receive: (channel, func) => {
        ipcRenderer.on(channel, (event, ...args) => func(...args));
    },
});
// package.json

  "build": {
  "appId": "com.example.test",
  "productName": "test",
  "files": [
    "dist/**/*",
    "node_modules/**/*",
    "main.js",
    "configs.json",
    "package.json",
    "Managers/**/*",
    "Images/**/*",
    "Pages/**/*",
    "Tasks/**/*",
    "renderer.js"
  ],
  "directories": {
    "output": "build"
  }
}

Testing undefined, failing in JS

In an Express app I have the following JS code (server side) in a middleware to check that a user provides an adequate token. This is only the relevant part for my question:

const authHeader = req.headers['authorization']
console.log("authHeader : ", authHeader)

if (authHeader === undefined) console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (authHeader == undefined) console.log("authHeader == undefined")
else console.log("authHeader != undefined")

if (authHeader.valueOf() === undefined) console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (authHeader.valueOf() == undefined) console.log("authHeader == undefined")
else console.log("authHeader != undefined")

if (typeof authHeader === 'undefined') console.log("authHeader === undefined")
else console.log("authHeader !== undefined")

if (typeof authHeader == 'undefined') console.log("authHeader == undefined")
else console.log("authHeader != undefined")

As one can see the code above does not do much, except getting an incoming parameter, and testing it, but here is the result in the server logs:

app[web.1]: authHeader :  undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined
app[web.1]: authHeader !== undefined
app[web.1]: authHeader != undefined

The console.log() shows that authHeader is undefined.
But none of the following tests confirms that.
They all show authHeader as not undefined.

Why is that ?

I have used all the possible ways I could think of to do the test but it seems they are all wrong.

P.S.

Knowing the way I do the test, I expect authHeader to be undefined.

What I do not expect is that none of the test would say so.

How to connect to MongoDB successfully from ReactJS?

I would like to know how to connect to MongoDB successfully as I am facing several issues when attempting the connection. The code is displayed below:

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const ecommerceSchema = require('./components/Login/Users');

const app = express();
app.use(express.json());
app.use(cors());

mongoose.connect("mongodb://localhost:27017/ecommerce-test");

app.post('/users', (req, res) => {
         UsersModel.create(req.body)
        .then(ecommerce => res.json(ecommerce))
        .catch(err => res.json(err))
  })

app.post('/users', (req, res) => {
  const{email, password} = req.body;
  UserModel.findOne({email: email})
  .then (ecommerce => {
    if(ecommerce) {
      if (ecommerce.password === password) {
        res.json("Success")
      } else {
        res.json("the password is incorrect")
      }
    } else {
      res.json("No record existed")
    }
  })
}
)

app.listen(3001, () => {
  console.log("server is running");
})

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

const Signin = () => {

    const [name, setName] = useState();
    const [email, setEmail] = useState();
    const [password, setPassword] = useState();
    const [addClass, setaddClass] = useState("");

    const handleSubmit = (e) => {
      e.preventDefault();
      axios.post('http://localhost:3001/users', {name, email, password}
        .then(result => 
          console.log(result)
        )
      )
        .catch(err => console.log(err))
    }

    const handleLogin = (e) => {
      e.preventDefault();
      axios.post('http://localhost:3001/Signin', {email, password})
        .then(result => {
          console.log(result)
          if(result.data === "Success") {
            navigate('/Home')
          }
      })
        .catch(err => console.log(err))
    }

  return (
  <div className='wrapper'>
     <div className={`container ${addClass}`} id='container'>
         <div className='form-container sign-up-container'>
            <form onSubmit={handleSubmit}>
                <h1>Create Account</h1>
                <input type="text" placeholder='name' onChange={(e) => setName(e.target.value)}/>
                <input type="email" placeholder='email' onChange={(e) => setEmail(e.target.value)}/>
                <input type="password" placeholder='password' onChange={(e) => setPassword (e.target.value)}/>
                <button type="submit">Submit</button>

            </form>
         </div>
            <div className="form-container sign-in-container">
              <form onSubmit={handleLogin}>
                <h1>Login</h1>
                <input type="email" placeholder='email' onChange={(e) => setEmail(e.target.value)}/>
                <input type="password" placeholder='password' onCharge={(e) => setPassword(e.target.value)}/>
                <button type="submit">Submit</button>
              </form>
            </div>
              <div className="overlay-container">
                 <div className="overlay">
                      <div className="overlay-panel overlay-left">
                        <button className="ghost" id="signIn" onClick={() =>setaddClass("")}>Go to Login
                        </button>
                      </div>
                      <div className="overlay-panel overlay-right">
                        <button className="ghost" id="signUp" onClick={() =>setaddClass("right-panel-active")} >Go to Register</button>
                      </div>
                 </div>
              </div>
     </div>
   </div>
  )
}
export default Signin

const mongoose = require('mongoose');

const ecommerceSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
});

const UsersModel = mongoose.model("ecommerce-test", ecommerceSchema)
module.exports = UsersModel;

I have more than 30 erros but I would like to know how to make it in order to register one user to the database and login and redirect to home page, please find database information in one picture attached below. I know my code is a mess, that’s the reason I need help: Mongodb_ecommerce Thanks for the help very appreciated.