CORS preflight error but I have installed cors and even set allow origin headers in Express

I have a client app that makes a fetch request to a server running at port 3333, however I get this error when I access the site after using port forwarding.

Access to fetch at 'http://localhost:3333/' from origin 'https://sdnxn5zx-3000.euw.devtunnels.ms' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

even after running locally I still get errors

Access to fetch at 'http://localhost:3333/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

and here is what my server file has in it

const express = require("express");
const app = express();
const cors = require("cors");

app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
    methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    headers: ["Content-Type", "Authorization"],
    maxAge: 84600,
  })
);
app.use((request, response, next) => {
  response.setHeaders({
    "Access-Control-Allow-Origin": "http://localhost:3000",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
    "Access-Control-Allow-Headers": "Origin, Content-Type, Accept",
  });
});

app.get("/", (request, response) => {
  response.json("Successful");
  console.log("Hello World");
});
app.listen(3333, () => {
  console.log("Server is running on port 3333");
});

What’s the mechanism that makes destructuring & rest parameter create an isolated copy, while rest parameter expose the original array to mutation?

function t(..._a) 
{
    console.log("t says:", _a[0] === a);    // Output:  t says: true
}

function v([..._a]) 
{
    console.log("v says:", _a === a);       // Output:  v says: false
}

const a = [{}, {}, {}];
t(a);
v(a);

What’s the exact mechanism, at memory level, that makes destructuring “[…_a]” create an isolated copy, while rest parameters “…_a” expose the original array to mutation?

why isn’t “[…_a]” equal to “_a[0]”?

Reformat an array of JSON objects in JavaScript [closed]

I’m receiving the array of JSON objects pasted below from an API call, and would like to reformat it in javascript so that I have a new/simplified array of JSON objects that include:
the attributes in Object1 (just those from ID through City), and the attributes that are in the ‘parent’ object (attributes from q1_response through Notes). I expect I could do with a loop, but was hoping for something more efficient and straightforward.

[
    {
        "attributes": {
            "type": "Survey",
            "url": "/xxxx/data/xxxx/xxxx/xxxxx/axxxxxxxxxx"
        },
        "Object1": {
            "attributes": {
                "type": "Incident",
                "url": "/xxxx/data/xxxx/xxxx/xxxxx/bxxxxxxxxxx"
            },
            "Id": "aaabbb00001",
            "Survey_Version": "V2.0",
            "Incident_type": "Call",
            "CreatedDate": "2025-04-24",
            "Service_Responded": true,
            "City": "Houston"
        },
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    },
    {
        "attributes": {
            "type": "Survey",
            "url": "/xxxx/data/xxxx/xxxx/xxxxx/axxxxxxxxxx"
        },
        "Object1": {
            "attributes": {
                "type": "Incident",
                "url": "/xxxx/data/xxxx/xxxx/xxxxx/bxxxxxxxxxx"
            },
            "Id": "aaabbb00002",
            "Survey_Version": "V1.0",
            "Incident_type": "Call",
            "CreatedDate": "2025-04-26",
            "Service_Responded": true,
            "City": "Dallas"
        },
        "q1_response": "Example q1 response",
        "q2_response": true,
        "q3_response": false,
        "Notes": "Example notes"
    }
]

Desired outcome:

[
    {
        "Id": "aaabbb00001",
        "Survey_Version": "V2.0",
        "Incident_type": "Call",
        "CreatedDate": "2025-04-24",
        "Service_Responded": true,
        "City": "Houston",
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    },
    {
        "Id": "aaabbb00001",
        "Survey_Version": "V2.0",
        "Incident_type": "Call",
        "CreatedDate": "2025-04-24",
        "Service_Responded": true,
        "City": "Houston",
        "q1_response": "Example q1 response",
        "q2_response": false,
        "q3_response": false,
        "Notes": "Example notes"
    }
]

I tried various versions of filter and reduce, but didn’t get the desired result.

Firebase Auth working on web but not on mobile or simulator

I am using React Native and Expo to write a typescript app. I’m trying to add auth through firebase, but I am running into errors. Here is my firebaseConfig:

// firebaseConfig.ts
import { initializeApp } from 'firebase/app';
import { initializeAuth } from 'firebase/auth';

import { getFirestore } from 'firebase/firestore'; // if you're using Firestore

const firebaseConfig = {...};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = initializeAuth(app, {});

I have also tried importing @firebase/auth and I have tried using getAuth() to no avail.

I am able to login and create accounts successfully on web, but on mobile/mobile simulator, I keep getting the following error for multiple files:

 WARN  Route "./login.tsx" is missing the required default export. Ensure a React component is exported as default.
 ERROR  Error: Component auth has not been registered yet, js engine: hermes
 WARN  Route "./signup.tsx" is missing the required default export. Ensure a React component is exported as default.

My login.tsx has a default export:

import { useState } from 'react';
import { router } from 'expo-router';
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from '@/firebaseConfig'; 
...

export default function LoginPage() { ...}

I am using the following dependencies:

  "dependencies": {
    "@expo/vector-icons": "^14.0.2",
    "@react-native-async-storage/async-storage": "^2.1.2",
    "@react-navigation/bottom-tabs": "^7.2.0",
    "@react-navigation/native": "^7.0.14",
    "date-fns": "^4.1.0",
    "expo": "^53.0.0",
    "expo-blur": "~14.1.4",
    "expo-constants": "~17.1.5",
    "expo-font": "~13.3.1",
    "expo-haptics": "~14.1.4",
    "expo-linking": "~7.1.4",
    "expo-router": "~5.0.5",
    "expo-splash-screen": "~0.30.8",
    "expo-status-bar": "~2.2.3",
    "expo-symbols": "~0.4.4",
    "expo-system-ui": "~5.0.7",
    "expo-web-browser": "~14.1.6",
    "firebase": "^11.7.3",
    "react": "19.0.0",
    "react-dom": "19.0.0",
    "react-native": "0.79.2",
    "react-native-gesture-handler": "~2.24.0",
    "react-native-reanimated": "~3.17.4",
    "react-native-safe-area-context": "5.4.0",
    "react-native-screens": "~4.10.0",
    "react-native-web": "^0.20.0",
    "react-native-webview": "13.13.5"
  },

ERR_UNSUPPORTED_DIR_IMPORT in webpack + typescript

I encountered error “ERR_UNSUPPORTED_DIR_IMPORT” when trying to call the script “webpack” in my project.
Thanks in advance to those who respond.

Used versions:
“webpack”: “^5.64.4”
“typescript”: “^4.9.5”
NodeJS: 23.7.0

Error text:

[webpack-cli] Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import 'C:Projectsproject-templatesJavaScriptwebpackwebpack-appwebpackConfig' is not supported resolving ES modules imported from C:Projectsproject-templatesJavaScriptwebpackwebpack-appwebpack.config.ts
    at finalizeResolution (node:internal/modules/esm/resolve:263:11)
    at moduleResolve (node:internal/modules/esm/resolve:860:10)
    at defaultResolve (node:internal/modules/esm/resolve:984:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:719:12)
    at #cachedDefaultResolve (node:internal/modules/esm/loader:643:25)
    at #resolveAndMaybeBlockOnLoaderThread (node:internal/modules/esm/loader:678:38)
    at ModuleLoader.resolveSync (node:internal/modules/esm/loader:701:52)
    at #cachedResolveSync (node:internal/modules/esm/loader:662:25)
    at ModuleLoader.getModuleJobForRequire (node:internal/modules/esm/loader:390:50)
    at new ModuleJobSync (node:internal/modules/esm/module_job:342:34) {
  code: 'ERR_UNSUPPORTED_DIR_IMPORT',
  url: 'file:///C:/Projects/project-templates/JavaScript/webpack/webpack-app/webpackConfig'
}
error Command failed with exit code 2.

webpack.config.ts file:

import { buildWebpack } from "./webpackConfig";

export const webpackConfig = (env, args) => {
    return buildWebpack(env, args);
}

./webpackConfig/index.ts file:

export * from "./webpackBuild";

I NEED directory imports and i tried this approaches:

  • Added “exports” in my package.json
        "exports": {
         "./*.ts": {
            "types": "./*.d.ts",
            "require": "./*.ts",
            "import": "./*.ts"
        }}
  • use index.ts file for export (above)
  • added Babel and babel.config.json file:
{
    "presets": ["@babel/preset-env"]
}

Not able to access environment variables (.env) in all the files. (node.js)

Everything works perfectly when I place the .env file in the root directory and call config() in the main.js. But the moment I move the .env file to the ./config directory, I have to call config({path: "config/.env"}) in every single file where I want to read environment variables from process.env.

Below are all my dependencies:

"dependencies": {
    "bcryptjs": "^3.0.2",
    "cookie-parser": "^1.4.7",
    "dotenv": "^16.5.0",
    "express": "^5.1.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.15.0"
  }
"devDependencies": {
    "@babel/preset-env": "^7.27.2",
    "concurrently": "^9.1.2",
    "morgan": "^1.10.0"
  }

Notes:

  1. I am using ES6 module.
  2. I have placed the import and function call on top before anything else, but still it’s not working.
  3. I have also placed import "dotenv/config" at the top.
  4. Node.js v22.12.0, npm v10.9.0.
  5. No errors in terminal.

Any help or tutorial/article link would be appreciated.

How to set result on a Promise outside of its constructor callback? [duplicate]

How do you resolve/reject a Promise outside of the constructor callback? My goal is to return a Promise that will later be resolved/rejected in the middle of a promise chain. E.g.,

function makeApiCall(form_data) {
    const out_promise = new Promise(); // Promise to return.
    // TypeError: Promise resolver undefined is not a function

    fetch(url, {body: form_data))
        .then(preprocessApiResponse)
        .then(async (response) => {
            out_promise.resolve(response); // Resolve created promise.
            //          ^ undefined
            return response;
        }, async (reason) => {
            out_promise.reject(reason); // Reject created promise.
            //          ^ undefined
            return error;
        })
        .finally(cleanupApiResponse);

    return out_promise;
}

response = await makeApiCall(form_data);

How to set result on a Promise outside of its constructor callback?

How do you resolve/reject a Promise outside of the constructor callback? My goal is to return a Promise that will later be resolved/rejected in the middle of a promise chain. E.g.,

function makeApiCall(form_data) {
    const out_promise = new Promise(); // Promise to return.
    // TypeError: Promise resolver undefined is not a function

    fetch(url, {body: form_data))
        .then(preprocessApiResponse)
        .then(async (response) => {
            out_promise.resolve(response); // Resolve created promise.
            //          ^ undefined
            return response;
        }, async (reason) => {
            out_promise.reject(reason); // Reject created promise.
            //          ^ undefined
            return error;
        })
        .finally(cleanupApiResponse);

    return out_promise;
}

response = await makeApiCall(form_data);

Unable to Overwrite File with Node fs

I am working on a TypeScript library generates API documentation (using jsdoc-to-markdown) and I am trying to do some post-processing of the files after they are all generated. Everything is working correctly except when I try to overwrite the file, the file is not updated. However, if I write the data to a new file, then I see my changes.

async function processFiles() {
  try {
    const codeElementPattern = /<code>(.+?)</code>/g;
    const codeElementNamePattern = />(.+?)</;

    let fileData = "";

    for (const [, { formattedPath }] of classFileMap) {
      fileData = await fs.promises.readFile(formattedPath, {encoding: "utf8", flags: fs.constants.O_RDWR});

      const matches = fileData.match(codeElementPattern);

      for (const match of matches) {
        const nameValue = match.match(codeElementNamePattern);
        const documentPath = classFileMap.get(nameValue[1]);

        if (documentPath === undefined || documentPath === null) {
          continue;
        }

        fileData = fileData.replace(
          match,
          `[${nameValue[1]}](${documentPath.relativePath})`,
        );
      }

      await fs.promises.writeFile(formattedPath + 'd', fileData); // <-- Writes changes correctly to new file
      await fs.promises.writeFile(formattedPath, fileData); //<-- Does not update existing file
    }
  } catch (err) {
    console.warn(`Unable to process file ${formattedPath} - Error:n${err}`);
  }
}

I have tried using the following options to overwrite the existing file, but none worked:

  • { encoding: "utf8", flags: fs.constants.O_TRUNC | fs.constants.O_WRONLY }
  • { encoding: "utf8", flags: fs.constants.O_TRUNC | fs.constants.O_RDWR }
  • { encoding: "utf8", flags: fs.constants.O_TRUNC }
  • { encoding: "utf8", flags: 'w'}

I have also tried it with no options (i.e., default options) from both the file write call as well as the read call, without success, and no exceptions are thrown which could help me figure out what is going wrong.

As the new file (the one with the d appended to the file name/path) has the correct data, this is an issue with the overwriting call.

How can I update the client with information about the state of the currently active form request in sveltekit?

I am making a web app which sends some requests to external APIs which can take some time to complete. The user types information in a form, which is received by a +page.server.ts file in the default form action. Once it is done processing the request, information is displayed to the user.

However, since this takes so long, I wanted to add some messages that I can send to the client to display while they wait to inform them of the status of their request.

Below is a pseudocode-style representation of the functionality I am looking for:

+page.server.js

export const actions = {
  default: async ({ request }) => {
    sendClientMessage("I'm processing your request!")

    await processSomething()
    sendClientMessage("Thing 1 done!")

    await processOtherThing()
    sendClientMessage("Thing 2 done!")
  }
}

+page.svelte

<script>
  onClientMessage((message) => {
    console.log(`Got message from server: ${message}`)
  }
</script>

I’ve seen people suggest using things like websockets and socket.io. This sounds sort of like what I want, but from what I’ve seen, these require some pretty complicated manual client management to avoid sending messages to every connected client. Is there any simple-ish library that achieves the results I want, or are these going to be my only options? I don’t really need two-way communication as the only details the user sends are in the initial request.

Perhaps more importantly, is all of this effort worth it for relatively little functionality?

If anyone has any ideas or advice, it would be greatly appreciated. 🙂

I can’t seem to get .waitForDisplayed/exists methods to work for elements the moment i switch between apps

const el = browser.$(‘//android.view.View[@content-desc=”Login”]’);
await el.waitForDisplayed({timeout:5000});

if this snippet gets executed without shifting between apps, it works like a charm but i can’t seem to get it working when i transition between chrome and the native app.

I’m changing the context as well and i’m making sure that the context is indeed changed before sending commands.
I’ve tried managing different sessions for each app but it messes with the global browser session as it performs DELETE on the original browser and fails the test on completion hooks.

This is what i get in the terminal.

INFO webdriver: DATA {
[0-0]   script: 'checkVisibility(...) [612 bytes]',
[0-0]   args: [
[0-0]     {
[0-0]       'element-6066-11e4-a52e-4f735466cecf': '00000000-0000-007f-0000-008f00000003',
[0-0]       ELEMENT: '00000000-0000-007f-0000-008f00000003'
[0-0]     },
[0-0]     {
[0-0]       withinViewport: false,
[0-0]       contentVisibilityAuto: true,
[0-0]       opacityProperty: true,
[0-0]       visibilityProperty: true
[0-0]     }
[0-0]   ]
[0-0] }
[0-0] 2025-05-23T14:57:44.794Z ERROR webdriver: WebDriverError: Method is not implemented when running "execute/sync" with method "POST" and args "function checkVisibility(elem, params) {
[0-0]       if (typeof elem.checkVisibility === "function") {
[0-0]         return elem.checkVisibility(params);
[0-0]       }
[0-0]       return null;
[0-0]     }"

Maintain Aspect Ratio with CSS instead of JavaScript [duplicate]

I’m currently using flex to layout a series of buttons in a wrapper container.

The regular buttons get their widths and heights based on the padding and the inner text, but the image button gets its height set to 100%.

The problem I’m having is that the only way I’ve been able to maintain the square aspect ratio of the image button is by setting its width to its height using JavaScript.

I was wondering if there is a way to do this with CSS instead.

JSFiddle : https://jsfiddle.net/2qdbvr93/

makeSquare(".image button");
window.addEventListener("resize", () => {
  makeSquare(".image button");
});

function makeSquare(selector) {
  const buttons = document.querySelectorAll(selector);
  buttons.forEach((button) => {
    button.style.width = `${button.offsetHeight}px`;
  });
}
.wrapper {
  display: flex;
  align-items: stretch;
}

.regular button {
  padding: 20px 40px;
  background-color: #aaaaaa;
}

.image button {
  height: 100%;
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT7vnGsgBgV8QW50dp-wZ4GoCNWu4egKYuxAw&s");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}
<div class="wrapper">
  <div class="regular">
    <button>RegA</button>
  </div>

  <div class="image">
    <button></button>
  </div>

  <div class="regular">
    <button>RegB</button>
  </div>
</div>

UPDATE

I did try to get this working with css aspect-ratio, but didn’t have any success. I’m not sure it works with a dynamic height.

create and add multiple users to different shared Google drives

How to create and add multiple users to different shared Google drives in Google script according to the Department?.
A list of departments and user names and passwords will be issued on a separate Google sheet.
A list of groups and google drive’s ID will be issued on a separate Google sheet in the table.

I use this script but it works only to create users and add them to groups but not to drives.

function createUserAndAssignRoles() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  const userSheet = sheet.getSheetByName("User Data");
  const configSheet = sheet.getSheetByName("Configuration");

  const users = userSheet.getDataRange().getValues();
  const configData = configSheet.getDataRange().getValues();

  const teamGroups = {};
  const teamDrives = {};
  const teamDriveRoles = {};
  const locationGroups = {};

  configData.forEach(row => {
    const type = row[0];
    const name = row[1];
    const groupEmails = row[2] ? row[2].split(',').map(e => e.trim()) : [];
    const driveId = row[3] || '';
    const driveRole = row[4] || '';

    if (type === 'Team') {
      if (!teamGroups[name]) teamGroups[name] = [];
      if (!teamDrives[name]) teamDrives[name] = [];
      if (!teamDriveRoles[name]) teamDriveRoles[name] = [];

      teamGroups[name] = teamGroups[name].concat(groupEmails);
      if (driveId) {
        teamDrives[name].push(driveId);
        teamDriveRoles[name].push(driveRole);  // can be empty string
      }
    } else if (type === 'Location') {
      if (!locationGroups[name]) locationGroups[name] = [];
      locationGroups[name] = locationGroups[name].concat(groupEmails);
    }
  });

  for (let i = 1; i < users.length; i++) {
    const row = users[i];
    const firstName = row[0];
    const lastName = row[1];
    const email = row[2];
    const password = row[3];
    const team = row[4];
    const location = row[5];

    createGoogleUser(email, firstName, lastName, password);

    if (team && teamGroups[team]) {
      teamGroups[team].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }

    if (team && teamDrives[team] && teamDriveRoles[team]) {
      teamDrives[team].forEach((driveId, index) => {
        let role = teamDriveRoles[team][index] || 'reader';  // Default role
        addUserToDrive(email, driveId, role);
      });
    }

    if (location && locationGroups[location]) {
      locationGroups[location].forEach(groupEmail => {
        addUserToGroup(email, groupEmail);
      });
    }
  }
}

function createGoogleUser(email, firstName, lastName, password) {
  try {
    AdminDirectory.Users.insert({
      primaryEmail: email,
      name: { givenName: firstName, familyName: lastName },
      password: password,
      orgUnitPath: "/",  // Change if you use a custom OU
      changePasswordAtNextLogin: false
    });
    Logger.log('User created: ' + email);
  } catch (error) {
    Logger.log('Error creating user ' + email + ': ' + error.message);
  }
}

function addUserToGroup(email, groupEmail) {
  try {
    AdminDirectory.Members.insert({
      email: email,
      role: 'MEMBER'
    }, groupEmail);
    Logger.log('User added to group: ' + groupEmail);
  } catch (error) {
    Logger.log('Error adding user to group: ' + error.message);
  }
}

function addUserToDrive(email, driveId, role) {
  try {
    const validRoles = ['reader', 'writer', 'commenter', 'fileOrganizer', 'organizer'];

    role = role.trim().toLowerCase();
    if (role === 'viewer') role = 'reader';  // Normalize alias
    if (!validRoles.includes(role)) {
      Logger.log(`Invalid role "${role}" for drive ${driveId}. Defaulting to "reader".`);
      role = 'reader';
    }

    Drive.Permissions.insert({
      type: 'user',
      role: role,
      emailAddress: email
    }, driveId, {
      sendNotificationEmail: false,
      supportsAllDrives: true
    });

    Logger.log('User added to drive: ' + driveId + ' with role: ' + role);
  } catch (error) {
    Logger.log('Error adding user to drive: ' + error.message);
  }
}