Can’t get response headers – javascript

I’m creating a site that sends requests to an API server via JavaScript, in one of the requests it requires me to capture a token that is given to create changes to shopping carts, without this token you get a 403 response. The response headers have “access-control-allow-origin: *” which should allow me to get what I need from the headers, but it just wont pass over to my program with headers.get function. Changing the header identifier to use ”, lowercase, different uppercase or anything else doesn’t create any different results for me in the get function.

this is my code:

Code
Response Headers
Console.log output

This has been written following the API and support guidance, but I can’t get the token to pass. Support also made this same request on their side, and was able to get the token, so I’m completely baffled what is wrong on my side.

How to recreate browser zoom in a react project

I’m searching for a zoom that works exactly the browser’s zoom.

I’ve tried some but in the 3D viewer (three.js) the zoom is breaking the page.

I have to set the zoom at 80%, doing it directly from the browser Zoom perfectly works but setting it from code works for all the pages excluding the 3d viewer

i’v tried with

zoom: 0.8;

transform: scale(0.5)

document.body.style.zoom = "80%"

How to pass refs to lazy load components

Hello guys I’m trying to pass refs to lazy load component but getting null instead of {current: null} please check where I’m doing mistake.

'use client';
import dynamic from 'next/dynamic';
import { useRef } from 'react';
const Component = dynamic(() => import('../components/Component'), {
  ssr: false,
});

export default function Home() {
  const ref = useRef(null);
  return <Component ref={ref} />;
}

import { forwardRef, useEffect } from 'react';
const Component = forwardRef((props, ref) => {
  useEffect(() => {
    console.log(ref);
  }, []);
  return <h1>Practice</h1>;
});
export default Component; 

I’m expecting {current: null} this output in Component

How to style light and dark mode in web components with user / OS settings

Since I don’t know a way to style a web component with parent lightDOM class selector to choose which is the theme selector (light or dark) i’ve found a way to choose it via custom property:

The HTML page

<html style="--global-pref-theme:dark;">
  <my-component></my-component>
</html>

My web component

<host>
 <div class="tabs">
   ... 
 </div>
</host>

Web component CSS

.tabs {
  background-color: #ffffff;
}

@container style(--global-pref-theme: dark) {
  .tabs {
    background-color: #000000;
  }
}

This approach would be great but it ignores the operating system settings when the user chooses and forces me to add media query rule and potentially duplicate a lot of CSS code:

Web component CSS


.tabs {
  background-color: #ffffff;
}

@container style(--global-pref-theme: dark) {
  /* user select only */
  .tabs {
    background-color: #000000;
  }
}

@media (prefers-color-scheme: dark) {
  /* OS only */
  .tabs {
    background-color: #000000;
  }
}

I can’t use a list of query selectors but it would be nice:


.tabs {
  background-color: #ffffff;
}

@container style(--global-pref-theme: dark),
@media (prefers-color-scheme: dark) {
  /* both user select and OS */
  .tabs {
    background-color: #000000;
  }
}

Is there some way to do it and avoid duplicate CSS code?

I’m open to tailwind, postcss or rollup solutions if necessary (I’m using stencil).

I would avoid a javascript way cause i have 75 web components to be styled and this would be awful for me.

VS Code: Open an existing folder in a container throws an error

I’ve created a simple Deno App using Hono and successfully deployed to a Docker Container using the following dockerFile which is copied from docker.com

FROM denoland/deno:1.46.0

EXPOSE 1993

WORKDIR /app

USER deno

COPY deps.ts .
# RUN deno cache deps.ts

# These steps will be re-run upon each file change in your working directory:
COPY . .
# RUN deno cache main.ts

CMD ["run", "--allow-net", "main.ts"]

I’ve been trying to open this as a container in VS Code following this tutorial. The first error was that it did not recognise the deno cache command so I commented it out.

When I ran this again it choked on its own devcontainer.json config file. To fix this I deleted all the comment lines so it read.

{
    "name": "Existing Dockerfile",
    "build": {
        "context": "..",
        "dockerfile": "../Dockerfile"
    }
}

I now get the following error which I a struggling to resolve.

Command in container failed: mkdir -p '/home/deno/.vscode-server/bin' && ln -snf '/vscode/vscode-server/bin/linux-arm64/f1e16e1e6214d7c44d078b1f0607b2388f29d729' '/home/deno/.vscode-server/bin/f1e16e1e6214d7c44d078b1f0607b2388f29d729'

mkdir: cannot create directory '/home/deno': Permission denied

Has anyone else seen this error and is there a way to fix it?

Javascript development environment [closed]

I’ve inherited a web application in javascript and been tasked with developing various features for it. I’m completely unfamiliar with web development and have no idea what all the the buzzwords like Vue, Vite, yarn, etc mean (well, I guess yarn is a package manager that wraps npm?) so trying to find a sustainable way forward with this project is pretty daunting.

The current filesystem setup is like this:

project setup

The compose.yml builds and runs backend and frontend in separate containers and the app is served and ready to use.

Compose file:

services:
frontend:
build:
context: FrontEnd
args:
VITE_MAPBOX_TOKEN: $TOKEN
VITE_BE_URL: “http://localhost:8080” # PORT should be the same as open port to backend
VITE_WS_URL: “ws://localhost:8080/ws” # PORT should be the same as open port to backend
ports:
– 80:80
backend:
build:
context: BackEnd
environment:
NODE_ENV: development
PORT: 8080
ports:
– 8080:8080
networks:
– react-express
networks:
react-express:
driver: bridge
name: react-express

Currently the backend mostly makes GET and POST requests to hosts on my network and passes their response to the frontend which display the information, partly using react mapbox.

I’m getting tired of having to add print statements everywhere and toggling back and forth between my browser window and terminal when trying to debug stuff by finding out things like “what does this response look like”?

Whenever the frontend asks the backend to make a request and some element like ‘response.feature.data’ isn’t accessible becease ‘response.feature’ doesn’t exsist. I typically end up getting these errors in the developer panel in firefox:

enter image description here

After I potentially find and fix the bug I have to restart the containers, which is getting old.

I’ve been on a side project in parallel for a couple of weeks where we use yarn to set up a development environment by using the package-lock.json file. There, we defined some commands like “yarn run dev” – the application will launch, and I can modify the code in real time, it builds and the changes are immediately present in the app.

I’d like to have something similar for this project, but I don’t know what to do. So, that’s my question… How do I setup yarn for this project? Do I need to use yarn? What are my alternatives? Additionally, is the setup that they have created here typical for react projects? It seems like they chose to use docker out of convenience when deploying but it doesn’t serve me as well in development.

Theme Resume of Clarence Taylor: item in the sidenav may not appear active

Source: https://startbootstrap.com/theme/resume

If the section contains more text, the item in the sidenav may not appear active. To fix this issue, ensure that the sidenav’s active state is properly configured to accommodate content of varying lengths.

How can I do this?

rootMargin with different values don’t fix the problem

/*!
* Start Bootstrap - Resume v7.0.6 (https://startbootstrap.com/theme/resume)
* Copyright 2013-2023 Start Bootstrap
* Licensed under MIT (https://github.com/StartBootstrap/startbootstrap-resume/blob/master/LICENSE)
*/
//
// Scripts
//

window.addEventListener('DOMContentLoaded', event => {

    // Activate Bootstrap scrollspy on the main nav element
    const sideNav = document.body.querySelector('#sideNav');
    if (sideNav) {
        new bootstrap.ScrollSpy(document.body, {
            target: '#sideNav',
            rootMargin: '0px 0px -50%',
        });
    };

    // Collapse responsive navbar when toggler is visible
    const navbarToggler = document.body.querySelector('.navbar-toggler');
    const responsiveNavItems = [].slice.call(
        document.querySelectorAll('#navbarResponsive .nav-link')
    );
    responsiveNavItems.map(function (responsiveNavItem) {
        responsiveNavItem.addEventListener('click', () => {
            if (window.getComputedStyle(navbarToggler).display !== 'none') {
                navbarToggler.click();
            }
        });
    });

});

How can I implement a service worker to display notifications to users, even when they’re not actively on my website, in JavaScript?

“I’m trying to implement a service worker in JavaScript to display notifications to users, even when they’ve closed my website. However, my notifications aren’t appearing when closed. Can you provide guidance on how to troubleshoot this issue?”

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js',{ scope: "/" })
        .then(function(registration) {
            console.log('Service Worker registered with scope:', registration.scope);

        }).catch(function(error) {
        console.log('Service Worker registration failed:', error);
    });
} else {
    console.log('Service Worker or Background Sync is not supported in this browser.');
}

Website doesn’t have a robot.txt, but Lighthouse says ‘robots.txt is not valid’ and shows index.html as robot.txt

I didn’t add robot.txt to an Angular app (we don’t need it) and documentation says that it’s not necessary to add it.
But when I run a Lighthouse SEO check it says ‘robots.txt is not valid 62 errors found’ and shows content of index.html as robot.txt.
Looks like it generates robot.txt from index.html, how to stop it from doing it?

I can’t reproduce it locally, only on deployed environments

ui-select Dropdown Always Sends ‘true’ to Backend Regardless of Selection

I am working on an AngularJS project and have upgraded the library from ui-select2 to ui-select. I am specifically working on a dropdown, so I had the ui-select2 dropdown:

<select data-ui-select2="{allowClear: true}" ui-select2="clearDropDown" ng-model="isFinalSubmission" data-placeholder="Final Submission Done?" class="padding-left-right-zero">
   <option></option>
   <option value="true">Yes</option>
   <option value="false">No</option>    
</select>

I have now upgraded to ui-select dropdown:

<ui-select style="cursor: pointer;" ng-model="isFinalSubmission" theme="select2" 
class="padding-left-right-zero" search-enabled="true" 
ng-init="options = [{ value: 'true', label: 'Yes' },{ value: 'false' , label: 'No' }]">
   <ui-select-match allow-clear="true" placeholder="Final Submission Done?">{{$select.selected.label}}</ui-select-match>
   <ui-select-choices repeat="option.value as option in options | filter: $select.search">
      {{option.label}}
   </ui-select-choices>
</ui-select>

However, it is not working as expected. The dropdown value is displayed correctly when I click it, but when I perform an operation, the value sent to the backend is always the initial fixed value, which is not what I want.

Js File:

(function (window, angular, undefined) {
    'use strict';
    angular.module('angularModule.controllers').controller('searchHoldingCtrl', ['$scope', '$compile', '$window', 'ajaxCall', '$controller', 'checkPermissions', '$rootScope', '$location', 'permissionCheckService', 'fileDownloadService', 'holdingColumns','$timeout', function ($scope, $compile, $window, ajaxCall, $controller, checkPermissions, $rootScope, $location, permissionCheckService, fileDownloadService, holdingColumns, $timeout) {
        permissionCheckService.check('ETT_Reports_View');
        //Injecting common useful values to the scope
 $controller('commonCtrl', { $scope: $scope });
        $scope.selectIsinList();
        $scope.searchIsin = { Id: null };
        $scope.selectOptionsEmployeePromise();
        $scope.searchEmployee = { Id: null };
        $scope.searchTimePeriod = {}
        $scope.searchClass = {}
        $scope.searchParentCompany = {};
        $scope.copyHoldingToOpening = {};
        $scope.searchTimePeriodType = {};
        $scope.isFinalSubmission = true;
        $scope.isTimePeriodShow = false;
        $scope.isHoldingdateShow = false;
 $scope.ExportAnnualHoldingPDFReport = function () {

            var url = "/ETT/Reports/ExportAnnualHoldingPDFReport";
            var emp = isValidObject($scope.searchEmployee) ? $scope.searchEmployee.Id : null;
            var time = isValidObject($scope.searchTimePeriod) ? $scope.searchTimePeriod.Id : null;
            var holdingDate = isValidObject($scope.model.searchHoldingDate) ? $scope.model.searchHoldingDate : "";
            var timePeriodTypeId = isValidObject($scope.searchTimePeriodType) ? $scope.searchTimePeriodType.Id : null;
            var isin = isValidObject($scope.searchIsin) ? $scope.searchIsin.Id : null;
            var classId = isValidObject($scope.searchClass) ? $scope.searchClass.Id : null;
            var parentCompanyId = isValidObject($scope.searchParentCompany) ? $scope.searchParentCompany.Id : null;
            var isFinalSubmission = isValidObject($scope.isFinalSubmission) ? $scope.isFinalSubmission : null;
            $rootScope.viewLoading = true;

            fileDownloadService.downloadFilePost(url, JSON.stringify({
                emp: emp,
                timePeriod: time,
                holdingDate: holdingDate,
                timePeriodTypeId: timePeriodTypeId,
                isin: isin,
                classId: classId,
                parentCompanyId: parentCompanyId,
                isFinalSubmission: isFinalSubmission
            })).then(function (data) {
                if (!angular.isUndefined(data) && data.IsError == true) {
                    alertify.error(data.Message);
                    $rootScope.viewLoading = false;
                    return;
                }
                else {
                    $rootScope.viewLoading = false;
                }
            });
        }

        //Search
        $scope.gridconfig.getData = function (e) {
            $scope.gridconfig.isLocalData = true;
            $scope.model.RowsPerPage = $scope.reset ? 20 : e.data.pageSize;
            $scope.model.PageNumber = $scope.reset ? 1 : e.data.page;

            var emp = $scope.searchEmployee == undefined ? null : $scope.searchEmployee.Id;
            var time = $scope.searchTimePeriod == undefined ? null : $scope.searchTimePeriod.Id;
            var holdingDate = $scope.model.searchHoldingDate == undefined ? "" : $scope.model.searchHoldingDate;
            var timePeriodTypeId = $scope.searchTimePeriodType == undefined ? null : $scope.searchTimePeriodType.Id;
            var isin = $scope.searchIsin == undefined ? null : $scope.searchIsin.Id;
            var classId = $scope.searchClass == undefined ? null : $scope.searchClass.Id;
            var parentCompanyId = $scope.searchParentCompany == undefined ? null : $scope.searchParentCompany.Id;
            var isFinalSubmission = $scope.isFinalSubmission == undefined ? null : $scope.isFinalSubmission;
            $rootScope.viewLoading = true;
            ajaxCall.get('/ETT/Reports/SearchHoldings?emp=' + emp + '&timePeriod=' + time + '&holdingDate=' + holdingDate + '&timePeriodTypeId=' + timePeriodTypeId + '&isin=' + isin + '&classId=' + classId +
                '&parentCompanyId=' + parentCompanyId + '&isFinalSubmission=' + isFinalSubmission).then(function (data) {

                    if (angular.isUndefined(data) && data == null) {
                        $scope.holdingDataSource = [];
                        return;
                    }
                    if (!data.IsError) {
                        $scope.holdingDataSource = data.SearchResults;

                        $scope.gridconfig.ds = getRecordsForPage($scope.holdingDataSource, $scope.model.PageNumber, $scope.model.RowsPerPage);
                        $scope.gridconfig.dataCount = $scope.holdingDataSource.length;
                        e.success({ data: $scope.gridconfig.ds, total: $scope.gridconfig.dataCount });
                        $rootScope.viewLoading = false;
                    }
                    else {
                        alertify.error(data.Message)
                        $rootScope.viewLoading = false;
                    }
                });
        };

    }]);
})(window, window.angular);

What I Have Tried:

  • Checked the ui-select documentation to ensure proper configuration.
  • Verified that isFinalSubmission contains the expected data.

Issue:

It shows “true” in the backend even when “No” is selected.

Expected Behavior:

The dropdown should correctly reflect the selected option and send the appropriate value to the backend.

How to use anyof statement for required parameters in OpenAi Function calling

I am creating a function using open ai function calling that generates a json as output when a user confirms that they had the meal or not. I initially wanted that if a user uploads an image i would return the calories of that meal with the file_id of that image but now I want to it handle that cases where the user confirms without an image so I tried setting the required parameter for it but it giving me error that anyof can’t be used

if(true) {
    returnData.push({
      name: gptFunctions.GPT_FUNCTION_MEAL_CALORIES,
      description: 'If the user confirms they had the meal, find out the calories in that meal. The confirmation can be inferred even if the user response is not a simple yes. Ensure the context is relevant to having a meal. If an image is uploaded, ensure it is related to food and nutrition, and estimate calories from it. Only generate calories if it was explicitly asked by the user. Confirm the meal before generating calories. If the user confirms the same meal again with the same calorie value, notify them that it is already confirmed. This function should work for both text-based and image-based meal confirmations.',
      parameters:{
        type:'object',
        properties:{
        had_meal:{
          type:'boolean',
          description: 'Value is true if they had the meal, else it is false.'
        },
        date: {
          type: 'string',
          description: 'Date and time at which the user had the meal in YYYY-MM-DD HH:mm:ss format (24-hour format).',
        },
        calories:{
        type: 'integer',
        description: 'Estimated number of calories in the food item the user had.'
        },
        protein:{
          type: 'integer',
          description: 'Estimated protein content in the food item the user had.'
          },
        fat:{
          type: 'integer',
          description: 'Estimated fat content in the food item the user had.'
          },
        carbohydrate:{
          type: 'integer',
          description: 'Estimated carbohydrate content in the food item the user had.'
          },
        mealname:{
          type: 'string',
          description: 'Name of the meal.'
        },
        file_id:{
          type: 'string',
          description: 'File ID of the food item for which calories are to be estimated. This is required only if an image is uploaded.'
        },
        message:{
          type: 'string',
          description: 'Content of the user message. This is required if no image is uploaded.'
        },
        user_id:{
          type: 'string',
          description: 'ID of the user who confirmed the meal. This is required if no image is uploaded.'
        }
      },
      required: ['had_meal', 'date', 'calories', 'protein', 'fat', 'carbohydrate', 'mealname'],
      anyOf: [
        { required: ['file_id'] },
        { required: ['message', 'user_id'] }
      ]
      }
    });
  }

And this the error

error: BadRequestError: 400 Invalid schema for function 'saveCalories': schema must have type 'object' and not have 'oneOf'/'anyOf'/'allOf'/'enum'/'not' at the top level.

I tried finding documentation about it but couldn’t find anything about it

How to make input fields size immutable to padding changes?

I have a problem with the input fields causing increase on the height property when the padding is increased on them via function triggers from events. I want the size of the input fields to remain immutable regardless of the font and padding change through functions:

I tried setting the fixed height and box-sizing to border-box as shown above but the padding still increases the input height.

function focusInput() {
  for (let i of inputs) {
    i.style.padding = '1rem 1rem 2rem';
  }

  style.innerHTML = style.innerHTML.replace(
    /.input::placeholders*{[^}]+}/,
    '.input::placeholder { font-size: 12px; }'
  );
}

function clearInput() {
  for (let i of inputs) {
    i.style.padding = '';
  }

  style.innerHTML = style.innerHTML.replace(
    /.input::placeholders*{[^}]+}/,
    '.input::placeholder { font-size: 14px; }'
  );
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box
}

.form {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: linear-gradient( 90deg, rgba(70, 125, 179, 1) 0%, rgba(2, 31, 59, 1) 100%);
  padding: 5em;
  border-radius: 6em 1em 6em;
  display: flex;
  flex-direction: column;
  gap: 3em;
  box-shadow: 10px 10px 20px 0px rgba(0, 0, 0, 0.3);
}

.input {
  height: 3rem;
  min-width: 14rem;
  width: 70%;
  outline: none;
  border-radius: 4px;
  padding: 1rem;
  margin-bottom: 0.5rem;
}
<div class="form" id="forma">
  <h1>Sign Up</h1>
  <div id="inputs" style="line-height: 2.5em">
    <input class="input" type="email" name="emailOrPhone" placeholder="Email or phone number" />
    <input class="input password" type="password" placeholder="Password" maxlength="12" oninput="validateLength()" />
    <p class="error" id="error1"></p>
    <input class="input password" type="password" placeholder="Re-enter password" maxlength="12" oninput="isMatch()" />
    <p class="error" id="error2"></p>
  </div>

Javascript TinyMCE Post-Initialization Indentation Change

I am wokring with tinymce – great editor and very intuitive.

I want the ability to change the standard indentation px after initialisation. I am initialising like:

tinymce.init({
…,
indentation: “25px”,
})

This works perfectly and when the user indents – it indents with 25px. I want to be able to change this after initialisation.

I have looked through the tinymce.activeEditor attributes and have not found this setting.

Any ideas would be appreciated. Solutions would be even better.

Many thanks