JS Fetch-API response end with undefined [duplicate]

My goal is to fetch data from MySQL using PHP and Vanilla JS and populate an HTML table using list.js. Fetch is successfully retrieving the data in JSON format; however, I am not 100% sure it’s correct, but I am trying to mimic the example given.

Here is the basic outline of the JS:

function listCalendarEvents() {
    
    fetch('/google/listCalendarEvents/') // Replace with your API endpoint
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json(); // Assuming the response is JSON
      })
      .then(data => {
        // Handle the fetched data
        console.log(data.events);
        return data.events;
      })
      .catch(error => {
        // Handle errors
        console.error('There was a problem with the fetch operation:', error);
      });
}
const orders = listCalendarEvents();

which then sets the var “order” in window.List();

const orderList = new window.List(table, options, orders);

When the script is fired off, it retrieves the data from a PHP controller that outputs the JSON formatted data that I need like such:

public function listCalendarEvents()
{
    $events = $this->google_m->listCalendarEvents();
    echo json_encode(array('response' => 1, 'events' => $events));
    
    exit();
}

Once that data is retrieved, the HTML table displays undefined in each column. I made sure all variables and fields were correct. When using the static example of data below, it works… again, I’m not sure if the data is being formatted correctly.

Here is the console output:

(2) [{…}, {…}]
0
: 
dateTime
: 
"2024-10-24T07:00:00-07:00"
description
: 
null
endDate
: 
null
hangoutLink
: 
null
startDate
: 
null
summary
: 
"Meeting with Johnny Bravo"
[[Prototype]]
: 
Object
1
: 
{summary: 'November test for the GCAPI', description: null, startDate: null, endDate: null, dateTime: '2024-11-07T06:00:00-08:00', …}
length
: 
2
[[Prototype]]
: 
Array(0)

Any help would be great! Thank you!

Sample data which works:

const orders = [
  {
    id: 1,
    summary: 'order-dropdown-1',
    description: '#2181',
    hangoutLink: 'mailto:[email protected]'
  },
  {
    id: 2,
    summary: 'mailto:[email protected]',
    description: 'Milind Mikuja',
    hangoutLink: '10/03/2023'
  },
  {
    id: 3,
    summary: 'order-dropdown-3',
    description: '#2183',
    hangoutLink: 'mailto:[email protected]'
  }
];

Why do my React unit tests fail for my login form when I add a <Link to the register form? [duplicate]

I have several unit tests that test form validation for my login screen.

Example:

test("Invalid email renders error", async () => {
  render(<LoginForm />);

  // Arrange
  const emailElement = screen.getByTestId("email");
  const passwordElement = screen.getByTestId("password");
  const submit = screen.getByTestId("login-button");

  // Act
  await user.type(emailElement, "invalid");
  await user.type(passwordElement, "1234567890");
  fireEvent.click(submit);

  // Assert
  await waitFor(() => {
    expect(screen.getByText("Invalid email format")).toBeInTheDocument();
  });
});

But when I add this Link it fails:

<p>
  Don't have an account? <Link to="/Register">Register here</Link>
</p>
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

  88 |   test("Button was called with form values", async () => {
  89 |     const consoleSpy = jest.spyOn(console, "log");
> 90 |     render(<LoginForm />);
     |           ^
  91 |     //Arrange
  92 |     const emailElement = screen.getByTestId("email");
  93 |     const passwordElement = screen.getByTestId("password");

Any idea why the link text is causing this failure?

Here are the routes

function App() {
  return (
    <Routes>
      <Route path='/' element={<LoginForm />} />
      <Route path='Register' element={<RegisterForm />} />
    </Routes>
  );
}

exiftool-vendored: `extractBinaryTagToBuffer` Fails Unexpectedly

I want to read XMP data from PDFs in JavaScript:

const { exiftool } = require('exiftool-vendored');
const fs = require('fs');

async function extractXMPData(filename) {
    try {
        const buffer = await exiftool.extractBinaryTagToBuffer('XMP', filename);
        console.log(buffer.toString());
    } catch (error) {
        console.error('Error reading XMP data:', error);
    }

    // Close the exiftool instance to free resources
    await exiftool.end();
}

const filename = process.argv[2];
extractXMPData(filename);

That fails with “Error reading XMP data: Error: XMP not found”.

If I extract the XMP data on the command-line with exiftool -b -XMP /path/to/file.pdf, the XMP data is extracted. Also when I write the data to a file with JavaScript:

await exiftool.extractBinaryTag('XMP', filename, 'out.xpacket');

Is this a bug in exiftool-vendored or am I doing something wrong?

ECMAScript shows error after 1 successfull run of script in Openhab

Platform information:

Hardware: Synology with docker
OS: Linux/4.4.302+ (amd64)
Java Runtime Environment: debian 17.0.12
openHAB version: openHAB 4.2.2

Issue of the topic:
I have a rule that triggers when a widget (heating) changes the setpoint of a thermostat (evohome). The script of the rule is build on ecmascript (v11). It converts some variables + item value into a stringified JSON message on the command topic of the mqtt broker . When triggered a first time, the script runs and publishes a message on the broker, and changes te setpoint.
After that, the script is ‘broken’. It takes a while, and a reinitialize of the scriptengine makes it work again 1 time. I cannot get my head around why this is happening

Tried different things, depending on the various forums i checked on topics Javascript/JSON/MQTT/Graalvm/Openhab etc, but there isn’t a specific forum that discusses mqtt with evohome on Openhab 4.
Understand that the code works, and fires successfull, but only one time.

Code build up (complete rule):

configuration: {}
triggers:
  - id: "1"
    configuration:
      itemName: Thermostaat_zone_temperature_setpoint
    type: core.ItemStateUpdateTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >-
        var item = items.Thermostaat_zone_temperature_setpoint;

        var obj = new Object();

        obj.command = "set_zone_setpoint";

        obj.setpoint = item.state;

        obj.zone_idx = 1;

        obj.ctl_id = "ID";

        var val = parseFloat (obj.setpoint);

        obj.setpoint = val;

        var message = JSON.stringify(obj);

        var actions = actions.get("mqtt", "mqtt:broker:master");

        actions.publishMQTT("evohome/evogateway/_zone_independent/command",
        message);

        console.log(message);
    type: script.ScriptAction

Logging gives the following (Log when succesfull):

2024-10-17 20:17:02.354 [DEBUG] [.internal.OpenhabGraalJSScriptEngine] - Initializing GraalJS script engine...
2024-10-17 20:17:02.360 [DEBUG] [.internal.OpenhabGraalJSScriptEngine] - Injecting ThreadsafeTimers into the JS runtime...
2024-10-17 20:17:02.361 [DEBUG] [.internal.OpenhabGraalJSScriptEngine] - Evaluating cached global script...
2024-10-17 20:17:02.362 [DEBUG] [.internal.OpenhabGraalJSScriptEngine] - Evaluating cached openhab-js injection...
2024-10-17 20:17:02.417 [DEBUG] [.internal.OpenhabGraalJSScriptEngine] - Successfully initialized GraalJS script engine.
2024-10-17 20:17:02.420 [INFO ] [ab.automation.script.ui.evo_zone] - {"command":"set_zone_setpoint","setpoint":20.5,"zone_idx":1,"ctl_id":"id code"}
2024-10-17 20:17:02.420 [DEBUG] [ing.mqtt.internal.action.MQTTActions] - MQTT publish to evohome/evogateway/_zone_independent/command performed

Logging gives the following (Log when failed):

2024-10-18 06:51:42.850 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID 'evo_zone' failed: org.graalvm.polyglot.PolyglotException: TypeError: invokeMember (get) on org.openhab.binding.mqtt.internal.action.MQTTActions@27c6d6d2 failed due to: Unknown identifier: get
2024-10-18 06:54:44.350 [ERROR] [ation.script.javascript.evo_eetkamer] - Failed to execute script: TypeError: invokeMember (get) on org.openhab.binding.mqtt.internal.action.MQTTActions@27c6d6d2 failed due to: Unknown identifier: get
        at <js>.:program(<eval>:10)
        at org.graalvm.polyglot.Context.eval(Context.java:399)
        at com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.eval(GraalJSScriptEngine.java:458)
        at com.oracle.truffle.js.scriptengine.GraalJSScriptEngine.eval(GraalJSScriptEngine.java:426)
        at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:262)

JSDoc: Documenting a function with interdependent parameters

I have a function which takes in two parameters, something like:

function example(type, val) {
  // handle "val" based on "type"
}

The acceptable types for val depend on type. The type parameter will always be one of a few select strings. For example, my JSDoc may look something like the following:

/**
 * Handles the value of "val" based on the "type" parameter.
 * @function example
 * @param {"number" | "string" | "boolean"} type - The type of the "val" parameter.
 * @param { ????? } val - The value to handle.
 * @returns {void}
 */
function example(type, val) {
  // handle "val" based on "type"
}

It’s worth noting that "number", "string", and "boolean" aren’t actually the allowed values of type in my real code; I’m only using them here for demonstration as it makes the problem easier to understand.

As seen in the above code, type can take on a few select values. If type="number", for example, then val should only be allowed to be a number.

I thought I could union a few typedefs together to achieve the result I’m looking for, but I wasn’t entirely sure how this would even work as I’m dealing with functions, not objects.

Any suggestions would be appreciated!

Can’t load images from local files in React, React is trying to pull image from proxy?

I am currently building a small react webpage and the component I’m building returns one of two images based on whether a certain variable is null or not (it is supposed to hold the link to an image after an api request is made, but starts null). When that link isn’t available the code is supposed to return a different img object with an image locally available “camera.jpg”.

Unfortunately it looks like react is trying to call the proxy to my backend for the image even though I define the image with a local path. Any advice on how to fix it?

For reference here are my files

Image of file list for react app

Here is the warning telling me that react is looking in proxy for the image
Proxy error: Could not proxy request '/camera.jpg' from 'localhost:3000' to 'http://localhost:3001/'.

Img html object in code

<img
        id="imgHolder"
        src="./camera.jpg"
        alt="Something went wrong!"
        height="500"
        width="500"
      />

I have tried to look at different sources but I can’t tell if this is a problem with my js code or if I lack an understanding of how the proxy value functions in package.json. I want to see the image pop up but what I get instead is the alt text.

Progress Bar Based on % Towards Goal

I’m trying to make a progress bar that updates and shows how close the player is to being able to purchase an upgrade.

Apologizes if this is not formatted properly! First post.

Here’s what I have so far:

HTML:

<!-- Progress Bar -->
<div id="Progress">
  <div id="progressBar">1%</div>
</div>

CSS:

/* Progress Bar */
#Progress {
  width: 100%;    
  background-color: black;
}

#progressBar {
  width: 1%;
  height: 40px;
  background-color: purple;
  text-align: center;
  line-height: 40px;
  color: white;
}

What would I put for my JavaScript? I’ve tried along these lines:

document.getElementById("progressBar").style.width = (gameData.gems / gameData.prestigeMultiCost)

I’m aware that’s wrong and a mash up of a few concepts but I’m stumped on how to make this work.

Thanks!

EDIT: Here’s my latest batch of code. The goal is to make the background color go from white to a deep gold as you collect more diamonds, up to 1,000.

window.setInterval(function () {
    document.body.style.backgroundColor = " rgb (255, " + (255 - (gameData.diamonds * 0.039)) + ", " + (255 - (gameData.diamonds * 0.255)) + ")"
}, 10)

EDIT 2: I just had an extra space… I did it though!

overding an async function in odoo js

so I’m working on POS I added a custom qr code to the receipt generated but now I’m getting an encoding error because the async function to decode the image is set to time 0 – I want to override that function

the function is

odoo.define('point_of_sale.ReceiptScreen', function (require) {
    'use strict';

    const { Printer } = require('point_of_sale.Printer');
    const { is_email } = require('web.utils');
    const { useErrorHandlers } = require('point_of_sale.custom_hooks');
    const Registries = require('point_of_sale.Registries');
    const AbstractReceiptScreen = require('point_of_sale.AbstractReceiptScreen');
    const { useAsyncLockedMethod } = require('point_of_sale.custom_hooks');

    const { onMounted, useRef, status } = owl;


    const ReceiptScreen = (AbstractReceiptScreen) => {
        class ReceiptScreen extends AbstractReceiptScreen {
            setup() {
                super.setup();
                useErrorHandlers();
                this.orderReceipt = useRef('order-receipt');
                const order = this.currentOrder;
                const partner = order.get_partner();
                this.orderUiState = order.uiState.ReceiptScreen;
                this.orderUiState.inputEmail = this.orderUiState.inputEmail || (partner && partner.email) || '';
                this.orderUiState.isSendingEmail = false;
                this.is_email = is_email;

                onMounted(() => {

                    setTimeout(async () => {
                        if (status(this) === "mounted") {
                            let images = this.orderReceipt.el.getElementsByTagName('img');
                            for (let image of images) {
                                await image.decode();
                            }
                            await this.handleAutoPrint();
                        }
                    }, 0);
                });

I want to change it to

        await this.handleAutoPrint();  
    }
}, 1000); 

I tried extending the class but the first code runs then mine which should not be the case

Download all of the files from Inspect Element’s sources

I would like to download all of the .jpg images that I can see in Safari’s Inspect Element’s “sources” tab on one particular webpage.

I’ve been running this in the console:

(function () {
  function downloadFile(file) {
    const element = document.createElement('a');
    element.setAttribute('href', file);
    element.setAttribute('target', '_blank');
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }

  (new PerformanceObserver((list) => {
    list.getEntries().forEach((entry) => {
      if (entry.name.contains('.jpg')) {
        downloadFile(entry.name);
      }
    });
  })).observe({ type: "resource", buffered: true });
}());

I’m trying to use the Resource Timing API to get the list of sources, then I check “is this one one of the jpgs I want?” (false positives are fine), then it downloads it.

The problem is the downloading step: I can’t get the files to download. Replace the downloadFile(entry.name) line with console.log(entry.name) and I can see I’m pulling all the right URLs, but downloadFile(entry.name) does nothing as it is in the script at the moment, and on a previous attempt with an additional element.setAttribute('download', 'download') line Safari told me once for each of the jpegs: “The download atribute on anchor was ignored because its href URL has a different security origin.”

Is there a way I can download all the images on this webpage?

Unable to use property validity.typeMismatch for input

The form I’m trying to validate using the Constraint Validation API rules in Javascript is not working. My is set to

type = "email" 

however in my Javascript, I am unable to use the property I need which is validity.typeMismatch. This is an exercise to help me understand client-side form validation better.

const email = document.getElementById("mail");

email.addEventListener("input", (event) => {
  if (email.validity.typeMismatch) {
    email.setCustomValidity("I am expecting an email address!");
  } else {
    email.setCustomValidity("");
  }

});
body {
  background-color: #fff;
  color: #333;
  font: 1em / 1.4 Helvetica Neue, Helvetica, Arial, sans-serif;
  padding: 1em;
  margin: 0;
}

* {
  box-sizing: border-box;
}

input:valid {
  border: 2px solid green;
}

input:invalid {
  border: 2px solid red;
}
<body>
  <form>
    <label for="mail">I would like you to provide me with an e-mail address:</label>
    <input type="email" id="mail" name="mail" minlength="10" required>
    <button>Submit</button>
  </form>
</body>

I tried using ValidityState property, i expected it to allow me to use typeMismatch, but that did not work.

App crashing when i start with npm run dev

npm run dev

[email protected] dev
nodemon BackEnd/index.js

[nodemon] 3.1.7
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting node BackEnd/index.js
C:UsersFatiihDesktopBulgPayBackEndnode_modulesexpresslibapplication.js:217
throw new TypeError(‘app.use() requires a middleware function’)
^

TypeError: app.use() requires a middleware function
at Function.use (C:UsersFatiihDesktopBulgPayBackEndnode_modulesexpresslibapplication.js:217:11)
at Object. (C:UsersFatiihDesktopBulgPayBackEndindex.js:27:5)
at Module._compile (node:internal/modules/cjs/loader:1469:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

Node.js v20.18.0
[nodemon] app crashed – waiting for file changes before starting…

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

Node.js v20.18.0
[nodemon] app crashed – waiting for file changes before starting…

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

Node.js v20.18.0
[nodemon] app crashed – waiting for file changes before starting…

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

Node.js v20.18.0
[nodemon] app crashed – waiting for file changes before starting…

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Module._load (node:internal/modules/cjs/loader:1104:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:174:12)
at node:internal/main/run_main_module:28:49

Node.js v20.18.0
[nodemon] app crashed – waiting for file changes before starting…

My index.js:

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const sequelize = require('./config/database');
const User = require('./models/User');
const authRoutes = require('./routes/auth');

const bankAuth = require('./routes/bankAuth');
require('dotenv').config();

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Конфигуриране на сесията
app.use(session({
  secret: process.env.SESSION_SECRET || 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());

// Сега можеш да използваш bankAuth
app.use(bankAuth);

// Дефинирай основен маршрут (пример)
app.get('/', (req, res) => {
  res.send('Welcome to the BulgPay API');
});

// Стартиране на сървъра
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

// Увери се, че bankAuth е валиден маршрутен модул
app.use('/api', bankAuth); // Например, добави префикс за API

// Основен маршрут
app.get('/', (req, res) => {
  res.send('Welcome to the BulgPay API');
});


// Middleware
app.use(express.json());

// Тестов рут
app.get('/', (req, res) => {
  res.send('Financial App Backend');
});

// Синхронизиране с базата данни и стартиране на сървъра
sequelize.sync({ alter: true })
  .then(() => {
    console.log('Database connected and synced.');
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });


app.use('/api/auth', authRoutes);

const bankAuthRoutes = require('./routes/bankAuth');

app.use(passport.initialize());
app.use('/api/bank', bankAuthRoutes);

const paymentRoutes = require('./routes/payments');

app.use('/api/payments', paymentRoutes);

const helmet = require('helmet');
const rateLimit = require('express-rate-limit');

// Използване на Helmet за защита
app.use(helmet());

// Rate Limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 минути
  max: 100, // Максимален брой заявки от IP адрес
  message: 'Твърде много заявки от този IP адрес. Опитайте отново по-късно.'
});
app.use(limiter);

const logger = require('./config/logger');

// Пример за логване на грешка
app.use((err, req, res, next) => {
  logger.error(err.message);
  res.status(500).send('Сървърна грешка');
});

  

My bankAuth.js:

const express = require('express');
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2').Strategy;
const router = express.Router();
require('dotenv').config(); 

passport.use('bank', new OAuth2Strategy({
  authorizationURL: 'https://example.com/oauth2/authorize',  // Временен URL
  tokenURL: 'https://example.com/oauth2/token',  // Временен URL
  clientID: process.env.CLIENT_ID,
  clientSecret: process.env.CLIENT_SECRET,
  callbackURL: process.env.CALLBACK_URL || 'http://localhost:3000/auth/bank/callback'
},
function(accessToken, refreshToken, profile, done) {
  // Обработване на профила и токените (може да оставиш празно за сега)
  return done(null, profile);
}
));

// Сериялизиране на потребителя в сесията
passport.serializeUser(function(user, done) {
done(null, user);
});

// Десериализиране на потребителя от сесията
passport.deserializeUser(function(user, done) {
done(null, user);
});


// OAuth2 route за стартиране на аутентификацията
router.get('/auth/bank', passport.authenticate('oauth2'));

// Callback route, на който потребителят се връща след успешен login
router.get('/auth/bank/callback', 
  passport.authenticate('oauth2', { failureRedirect: '/login' }),
  function(req, res) {
    // Успешен login, пренасочваме потребителя
    res.redirect('/');
  }
);

// Примерен route за logout
router.get('/logout', function(req, res) {
  req.logout(function(err) {
    if (err) { return next(err); }
    res.redirect('/');
  });
});


// Примерен маршрут за аутентикация
router.get('/auth', passport.authenticate('oauth2'));

// Callback маршрут
router.get('/auth/callback', 
    passport.authenticate('oauth2', { failureRedirect: '/' }),
    (req, res) => {
        // Успешна аутентикация
        res.redirect('/');
    }
);


module.exports = passport;

I can’t understand what need to make.

Why is role_id from login not being forwarded in the getUsersForSidebar API request in my mern hierarchical chat app?

I’m working on a chat app where the user logs in through redirection from another portal. The authentication works fine, and the payload looks like this:

{

“fullName”: “Test Agent”,
“username”: “Test Agent”,
“email”: “[email protected]”,
“role_id”: 1,
“role”: “SuperAdmin”,
“handshakeToken”: “xxxxx.”
}

Login works on Postman, but when I try to fetch users for the sidebar using the getUsersForSidebar API, it returns all users, and the role hierarchy filtering is not applied. I realized that the role_id is not being forwarded properly.

Here’s the login controller:

    export const login = async (req, res) => {
  try {
    const { fullName, username, email, role_id, role, handshakeToken } = req.body;

    if (!fullName || !username || !email || !handshakeToken || !role_id || !role) {
      return res.status(400).json({ error: "Invalid payload. Ensure all required fields are provided." });
    }

    const expectedHandshakeToken = process.env.HANDSHAKE_TOKEN;
    if (handshakeToken !== expectedHandshakeToken) {
      return res.status(401).json({ error: "Invalid handshake token." });
    }

    const token = jwt.sign({ email }, process.env.JWT_SECRET, { expiresIn: '1h' });
    res.cookie("jwt", token, { httpOnly: true, secure: process.env.NODE_ENV === 'production' });
    return res.status(200).json({ message: "Login successful", token });
  } catch (error) {
    console.error("Error during login:", error);
    return res.status(500).json({ error: "Internal Server Error. Please check server logs for details." });
  }
};

The getUsersForSidebar controller looks like this:

    export const getUsersForSidebar = async (req, res) => {
  try {
    const currentUserEmail = req.user.email;
    const currentUser = await User.findOne({ email: currentUserEmail });

    const currentUserRoleId = currentUser.role_id;
    console.log("Current User Role ID:", currentUserRoleId); // This logs `undefined`

    const allUsers = await someApiCall();
    const filteredUsers = allUsers.filter(user => canInitiateChat(currentUserRoleId, user.role_id));

    res.status(200).json(filteredUsers);
  } catch (error) {
    res.status(500).json({ error: "Internal Server Error" });
  }
};

When I log currentUserRoleId, it shows undefined. However, if I manually set the role_id in the sidebar, the filtering works as expected. How can I ensure that the role_id from login is forwarded to the getUsersForSidebar API and used in filtering?

NativePHP + javascript event listening

Im having trouble with NativePHP and JS. As stated in the NativePHP docs

NativePHP injects a window.Native object into every window.

However

Native.on("Native\Laravel\Events\Windows\WindowFocused", (payload, event) => {
      alert("it works");
});

results in Uncaught ReferenceError: Native is not defined – clearly nothing is injected in Window. Can anyone help me, what am I missing…? Thank you.

getting error in google sign in using javascript

when im trying to sign in through google I’m able to proceed but at this point its showing blank strong text

    {% block content %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-signin-client_id" content="my client id">
    <title>Google Sign-In with JWT</title>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
    <h1>Google Sign-In</h1>
    
    <div id="g_id_onload"
         data-client_id = "my client id"
         data-callback ="handleCredentialResponse"
         data-login-uri = "http://127.0.0.1:8000/user/login/"
         data-auto_prompt ="false">
    </div>
    
    <div class="g_id_signin"
         data-type="standard"
         data-size="large"
         data-theme="outline"
         data-text="sign_in_with"
         data-shape="rectangular"
         data-logo_alignment="left">
    </div>

    <script>
        console.log("Current origin:", window.location.origin);

        function handleCredentialResponse(response) {
            console.log("Received response from Google Sign-In");
            const idToken = response.credential;
            console.log("ID Token:", idToken);

            fetch('http://127.0.0.1:8000/user/login/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ token: idToken }),
                credentials: 'include'
            })
            .then(response => {
                console.log("Received response from server");
                return response.json();
            })
            .then(data => {
                if (data.access) {
                    console.log("JWT Token:", data.access);
                    localStorage.setItem('jwt', data.access);
                    alert('Login successful!');
                } else {
                    console.error("Login failed:", data);
                    alert('Login failed!');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred during login');
            });
        }

        window.onload = function() {
            console.log("Page loaded. Google Sign-In should initialize soon.");
        };
    </script>
</body>
</html>

tried everything but not move ahead
using javascript more specifically HTML page to just get idToken from google and then sending it to backend for verification and other jwt generation

Why is my web page slow when serving offline using service worker caches?

I’m trying to make my webpage work completely offline, but I’m running into some issues with load time when trying to load from the cache

I’m currently caching all the files necessary for my website to run (about ~640kB in size, ~24 various text files), however the load time, when offline or online, is up to 2 minutes (or sometimes just completely times out, giving me this error: Error: {"columnNumber":-1,"lineNumber":-1,"message":"ServiceWorker startup timed out. The worker was in startup phase: Script streaming.","sourceURL":""})

(It loads just fine, even faster, without the caching.)

I’ve tried specifying which files to serve, as well as unregistering and reregistering the service worker multiple times.

The code for the service worker is below:

const CACHE_NAME = "webedit-testing-v2";

self.addEventListener('install', event => {
  console.log("Service worker: Installed.")

  self.skipWaiting()
})

self.addEventListener('activate', event => {
  console.log('Service worker: Activated.')

  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== CACHE_NAME) {
            console.log('Service worker: Deleting old caches.')
            caches.delete(cache)
          }
        })
      )
    })
  )
})

self.addEventListener('fetch', event => {
  console.log(`Service worker: Fetching ${event.request.url}`)
  event.respondWith(
    fetch(event.request)
      .then(res => {
        const resClone = res.clone()
        caches.open(CACHE_NAME)
          .then(cache => {
            cache.put(event.request, resClone)
          })
          return res
      })
      .catch(() => caches.match(event.request).then(res => res))
  )
})