How to set multiple routes files under the same subdomain in express-subdomain

I’m using express-subdomain to redirect routes to api subdomain.
I’ve two route’s files: auth.routes.js and utils.routes.js. I wanna that both route files are available under the subdomain api. I tried the pass an index file that is importing both of them, but it is not working. How can i do?

index.js
const authRouter = require("./auth.routes");
const utilsRouter = require("./utils.router");

module.exports = {
    authRouter,
    utilsRouter,
};


app.js
var apiRouter = require("./routes/testing/index");
app.use(subdomain("api", apiRouter));

Forcing an update from outside a React functional component (client side, using react.development.js)

I have a very simple https server I am talking to. It provides me with two calls (an authenticated GET and a POST for server-side storage of data). I am using two React functional components in my page. I load react.development.js so I can use React:

    <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

and at the end of my script I load the React functional components:

        // This one is so we get it from the 'server' the first time:
        // But it also prevents rendering, sadly
        //localStorage.removeItem( "reminders");
        const reminderRoot = ReactDOM.createRoot(document.getElementById('reminderset'));
        reminderRoot.render(<ReminderSet />);
        const loaderRoot = ReactDOM.createRoot(document.getElementById('jsoneditor'));
        loaderRoot.render(<JSONEditor />);

The commented call removes the data from localStorage on initial load of the page. This forces a fetch from the server. The rest of the time, if the data changes, it is POST-ed to the server and the localStorage item is updated.

One component starts with:

        const ReminderSet = () => {
            const [reminders, setReminders] = useState(getMyReminders());
            if (reminders === null || reminders === undefined || reminders === "" || reminders === "null") {
                return (
                    <div className="ReminderSet">
                        <p>Loading...</p>
                    </div>
                );
            }

As long as the fetch() result has not been handled, the component shows “Loading…”

And the function providing the reminders data element is like this:

        const getMyReminders = () => {
            let storedReminders = localStorage.getItem( "reminders");
            if (storedReminders === null || storedReminders === "") { // Check for empty string or null
                fillReminderStorageFromServer();
            }
            return JSON.parse(storedReminders);

When localStorage is still empty, the function fillReminderStorageFromServer() tries to get them. This uses fetch() (because it must authenticate) which is asynchronous, so I have to handle the return. This function looks like this:

        const fillReminderStorageFromServer = () => {
            const myHeaders = new Headers();
            const myToken = getToken();
            let jsonResponse;
            myHeaders.append( "Accept", "application/json");
            myHeaders.append( "Content-type", "application/json; charset=UTF-8");
            myHeaders.append( "Authorization", myToken);
            const myURL = window.location.protocol + "//" + window.location.host + "/checkdo-get";
            console.log( "GET: " + myURL);
            const fetchPromise = fetch(myURL, {
                  method: 'GET',
                  mode: 'same-origin',
                  redirect: 'error',
                  cache: 'no-cache',
                  headers: myHeaders,
                });
            fetchPromise.then((rawResponse) => {
                if (rawResponse.ok) {
                    const jsonPromise = rawResponse.json();
                    jsonPromise.then((jsonResponse) => {
                        localStorage.setItem( "reminders", JSON.stringify(jsonResponse));
                        // How do I get the component(s) to re-render?
                        // ReminderSet function component has: const [reminders, setReminders] = useState(getMyReminders());
                        // global script has: reminderRoot.render(<ReminderSet />);
                        window.dispatchEvent(window.alertEvent);
                    });
                }
            });
        }

My problem is, when this function finally has the data, it must update localStorage (which it does) and it must make the React components to re-render (which it doesn’t). I don’t know how to use setReminders from outside the React component. I’ve tried to solve this by using a window.alertEvent which is handled inside the React component:

            const forceUpdate = () => {
                console.log("FORCEUPDATE!");
            }
            window.addEventListener('forceUpdate',forceUpdate);

with

        window.alertEvent = new Event('forceUpdate');

at the start of my script. But the ‘FORCEUPDATE!’ log message is never seen.

As there are two React components on the page that use the same data, the data handling is outside both. But when the data arrives, I want to trigger an update of both components, which will mean I have to do something with setReminders or any other way. But how?

As it is now, it works when I uncomment the localStorage.removeItem( "reminders"); call. But the disadvantage of that is that when the server is used from different browsers, they will use (a possibly outdated) localStorage. So, if I can remove the localStorage cache when the page loads, but still get the component rendered correctly when the result of fetch() arrives, I have my working solution.

Antdesign disable tree tips

Is it possible to disable hover tooltips or customize it?. img

Try global css with next many variations, no result…

I couldn’t find anything in the documentation of the antd. The antd selector also has such an element by default.

Not getting any nutrient data from Nutritionix API requests

I am building a nutrition tracker app and would like to use a food database in order to search for a food and get its nutrient data (calories, protein, carbs, fat). Upon using Nutritionix I ran into the issue where the names of the foods come through just fine after making a request but the nutrient data property values are always undefined.

I tried this to fetch the data

const searchFood = async (query) => {
const url = `https://trackapi.nutritionix.com/v2/search/instant?query=${query}`;

  try {
    const response = await axios.get(url, {
      headers: {
        'x-app-id': appId,
        'x-app-key': appKey,
      },
    });

    // Process the response data to extract the nutrient details
    const searchResults = response.data.common.map((item) => ({
      name: item.food_name,
      calories: item.nf_calories,
      protein: item.nf_protein,
      carbohydrates: item.nf_total_carbohydrate,
      fats: item.nf_total_fat,
    }));

    setSearchResults(searchResults);
  } catch (error) {
    console.error('Error searching for food:', error);
    setSearchResults([]); // Return empty array in case of error
  }
};

and this to display it

<TouchableWithoutFeedback onPress={() => setModalVisible(false)}>
    <View style={styles.modalContainer}>
      <TouchableWithoutFeedback>
        <View style={styles.modalContent}>
          {/* Search food input field */}
          <View style={styles.searchContainer}>
            <TextInput
              style={styles.input}
              label="Search Food"
              value={searchQuery}
              onChangeText={setSearchQuery}
            />
            <TouchableOpacity onPress={handleSearch}>
              <Text style={styles.addButton}>Search</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.searchResultsContainer}>
            <FlatList
              data={searchResults}
              keyExtractor={(item, index) => index.toString()}
              renderItem={({ item }) => (
                <TouchableOpacity
                  onPress={() => handleAddFoodFromSearch(item)}
                >
                  <Text>{item.name}</Text>
                  <Text>Calories: {item.calories}</Text>
                  <Text>Protein: {item.protein}</Text>
                  <Text>Carbohydrates: {item.carbohydrates}</Text>
                  <Text>Fats: {item.fats}</Text>
                </TouchableOpacity>
              )}
              style={{ maxHeight: 200 }}
            />
          </View>

The nutrient data values are always undefined, so I am aware that there is no nutrient data being stored in these properties but is there any way around this?

How do I setup .env variables to use on client side?

I am trying to setup .env variables and don’t understand how to do it properly. I thought I needed to use webpack to access the variables but when I try to run the “webpack” command I get

 node:internal/modules/cjs/loader:1137
  throw err;
  ^

Error: Cannot find module 'resolve-cwd'
Require stack:
- /usr/share/nodejs/webpack/node_modules/import-local/index.js
- /usr/share/nodejs/webpack/node_modules/webpack-cli/bin/cli.js
- /usr/share/nodejs/webpack/bin/webpack.js

I have the following files:

config.js

// Parameters imported from .env file (environment variables)

const config = {
 apiBaseUrl : process.env.API_BASE_URL,
 oauth2BaseUrl : process.env.OAUTH2_BASE_URL,
 clientId : process.env.CLIENT_ID,
 redirectUrl : process.env.REDIRECT_URL,
};

// Use config values in your client-side code
console.log(config.apiBaseUrl);
console.log(config.oauth2BaseUrl);

authenticate.js



document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('button').addEventListener('click', redirectToLogin);
});

// Authorization code redirect initiated by 'login' event from Sign In button
function redirectToLogin() {
    // Must define all scopes needed for application
    const scope = encodeURIComponent('product.personalized cart.basic:rw profile.full');
    // Build authorization URL
    const url =
        // Base URL (https://api.kroger.com/v1/connect/oauth2)
        `${config.oauth2BaseUrl}/authorize?` +
        // ClientId (specified in .env file)
        `client_id=${encodeURIComponent(config.clientId)}` +
        // Pre-configured redirect URL (http://localhost:3000/callback)
        `&redirect_uri=${encodeURIComponent(config.redirectUrl)}` +
        // Grant type
        `&response_type=code` +
        // Scope specified above
        `&scope=${scope}`;
    // Browser redirects to the OAuth2 /authorize page
    window.location = url;
}

// Handle the call back from authorization server
function handleCallback() {
    const accessToken = cookies.get('accToken');
    const refreshToken = cookies.get('refToken');

    if (!accessToken) {
        return false;
    }
    // Store tokens client side for API requests
    storeTokens(accessToken, refreshToken);

    cookies.remove('accToken');
    cookies.remove('refToken');

    return true;
}


index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kroger Authentication</title>

    <script type="module" src="./authentication.js"></script>
    <script src="dist/bundle.js"></script>
</head>
<body>
    <button>Log In</button>


</body>
</html>

I get “Uncaught ReferenceError: config is not defined
at HTMLButtonElement.redirectToLogin (authentication.js:13:9)”

So I am trying to use webpack to get those.env variables to work in my authentication.js file but i am having no luck.

adding link to image with JS [closed]

I try to add a linnk to an image but somehow its not working. Where is my mistake?

 var imgElement = document.createElement("img");     
 imgElement.src = "https://www.starhit1fm.com/images/covers/wwac.jpg";
 imgEeight = 70;
 imgElement.width = 70;
 var container = document.getElementById("imageContainer");
 container.appendChild(imgElement);
 var a = document.createElement('a');
 a.href = "https://www.starhit1fm.com/worship.html";
 a.appendChild(imgageContainer);
 parent.parentNode.InsertBefore(a, parent.nextSibling);

event.target.id is not a function

my code seems to work. but when I click on a button, I get the error message event.target.id is not a function

this is my javascript code

var multiplyer = 1
var carparts = 0;
document.getElementById("karpartz").innerHTML = carparts;

function onButtonClick(event) {
if (event.target.id("car"))
 {carparts = carparts + multiplyer;
  document.getElementById("karpartz").innerHTML = carparts;}} 


const button = document.querySelector('button');
button.addEventListener('click', onButtonClick);

And this is my html:

<button id="car"type="submit">
  <img src="example" 
alt="buttonpng" border="0" />
</button>

<button id="clickpower">
  upgrade click power
</button>
<button id="">
  upgrade idle scrapping
</button>

<p id="karpartz"></p>

<html>

  <body>
    <h1>
      <script type="text/javascript">
        document.write(karpartz)

      </script>
    </h1>
  </body>

</html>


what do i do?

Exploring Options for a Document Editor Implemented Exclusively with Pure JavaScript and HTML

I am currently engaged in the development of a website wherein users are required to compose reports that necessitate conversion to the .docx format for subsequent emailing and printing. In pursuit of an adept document editor tailored to these specifications, I have explored commonly utilized options such as CKEditor and TinyMCE, yet these solutions do not align with the desired functionality. I am seeking recommendations for an alternative document editor that fulfills the specified requirements. Your assistance in guiding me towards a suitable solution would be greatly appreciated.

An approach to dissect an input Color; using 8+ static colors and finding their makeup percentage within the input color

I need to find an approach for dissecting a given input color, using given static colors (8 or more.. light yellow, violet, white, black, dark brown, teal etc.)

I want to find what percentage the static colors exist in the input color if at all, to gather the makeup.

Example: An RGB or hex color value is input, then passes are made to find out how much of the dark brown, white, teal, etc are used to make up that color exactly.

ex. Color A contains 40% white, 5% black, 35% dark brown, 0% teal, 15% bright yellow etc

I would like to recreate the input color using certain static colors. I know not all of the static colors can be used, and some would be more effective.

I suppose slider bars for the static colors could be used in order to match the input color visually, but that would not be fast enough, nor accurate.

Over a period of a few weeks, I have searched off and on for certain methods, and found nothing because the search terms give topics far from what i need to know.

‘user.uid is undefined’ while the id is available inside the user info array

Been struggling with retrieving the user.uid. I need it to construct a docRef. I suspect the user.uid is trying to be retrieved before all user data is loaded. I tried to include an await function, but I cannot make it work. The console log for users does include the uid in the array, so it is available. But it seems destructured? Is it a timing issue?

AS A user I WANT TO add an album to one of my Crates SO I CAN build a
collection of nice music.

The user can search for an album, and then click “Add to crate”, which calls the function below. The first console.log succesfully gets the user info, but the second one says user.uid is undefined.

export async function AddAlbumToCrateService(
  user: User,
  crateId: string,
  newAlbum: Album
): Promise<Album> {
  console.log('user (addAlbumToCrateService):', user);

  console.log('user.uid (addAlbumToCrateService):', user.uid);
  console.log('crateId (addAlbumToCrateService):', crateId);
  console.log('newAlbum (addAlbumToCrateService)):', newAlbum);

  const firestore = useFirestore();
  console.log('User after useFirestore at AddAlbumToCrateService' + user.uid);
  console.log('CrateId after useFirestore at AddAlbumToCrateService' + crateId)
  const crateRef = doc(firestore, 'users', user.uid, 'Crates', crateId);
  const albumsCollection = collection(crateRef, 'albums');



  try {
    // Include the timestamp when adding the Album
    const albumToAdd: Album = {
      ...newAlbum,
      timestamp: new Date(),
    };

    // Create a separate object for Firestore without the 'id' property
    const firestoreAlbum = { ...albumToAdd };

    // Add the Album to Firebase and get the reference
    const docRef = await addDoc(albumsCollection, firestoreAlbum);

    // Return the newly added Album with the generated ID
    const addedAlbum: Album = {
      id: docRef.id,
      ...albumToAdd,
    };

    return addedAlbum;
  } catch (error) {
    console.error('Error adding Album to Crate:', error);
    throw error;
  }
}

Canvas draw image method prevents ondataavailable from firing

Have a good day!

On localhost, I’m having a continuously changing img tag (I’ll explain more at the end) and am using a canvas to draw the image on it, so I can use MediaRecorder to capture the video-like image and save it.

The code I’m using is this:

var canvas2 = document.getElementById("canV");
var ctx = canvas2.getContext("2d");

// Start of marking

update();
function update(){
 ctx.drawImage(videos[0],0,0,640,480);
 requestAnimationFrame(update);
}

// End of marking

var videoStream = canvas2.captureStream(10); 
videoStream.getVideoTracks()[0].requestFrame();
var mediaRecorder = new MediaRecorder(videoStream);
var chunks = [];
mediaRecorder.ondataavailable = function(e) {
 chunks.push(e.data);
};
mediaRecorder.onstop = function(e) {
 var blob = new Blob(chunks, { 'type' : 'video/mp4' });
 chunks = [];
 var videoURL = URL.createObjectURL(blob);
 const video = document.createElement("video");
 video.src = videoURL;
 document.body.appendChild(video);
};

And I run the code below in console:

mediaRecorder.start(1000);

//After seconds

mediaRecorder.stop()

Note that the changing image is videos[0];

I perceived that the dataavailable event is only fired when I stop the mediaRecorder.
So I tried drawing other things on the canvas to debug it. I changed the part marked as “marking” in the snippet to:

var colors = ["red", "blue", "green"];
setInterval(update, 100);

function update(){
  ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
  ctx.fillRect(0, 0, 10, 10);
  ctx.drawImage(videos[0],0,0,640,480);
  requestAnimationFrame(update);
}

Until before, the blob is empty (I’m getting an error GET blob:http://local:8080/dbe7d1ac-1d97-4d4a-8921-2a0daa10d31a net::ERR_REQUEST_RANGE_NOT_SATISFIABLE) but after running this, I had a black background in the video generated, with a small red or blue or green square at the top left; it means the mediaRecorder records only the data when I run the stop method and si only recording the square not the drawImage, though; it still prevents dataavailable from firing.

Although, when I removed ctx.drawImage(videos[0],0,0,640,480); the event mentioned fires as expected.

So here comes two question, why the video doesn’t show the changing image and why the draw image method prevents mediaRecorder from firing dataavialable event?

FURTHER INFORMATION
The changing image actually is an IP Webcam (DroidCam on an android) and the source of that image is something like http://192.168.223.101:8080/video?640x480 and the image is actually a streaming camera in my cellphone.

Is it possible to be due to CORS or something?

And I’m not getting any more errors except the one I mentioned.

Any helps would be appreciated!

I am getting an error while try to use tensorflow to recognize faces

I am trying to use tensorflow to check if image has a human face
after user upload a photo

however I am getting this error:

RegPage.php:205 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘mediapipeFacemesh’)

will appreciate what I am doing wrong with code example.

attaching relevant code:

 <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
 <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/face-landmarks- 
detection"></script>

<script>


document.getElementById('take-photo').setAttribute('capture', 'environment');

// Change label text for taking a selfie photo
document.querySelector('label[for="take-photo"]').innerText = 'צלם תמונת סלפי:';

async function validateSelfie(input) {
if (input.files && input.files[0]) {
    const img = document.createElement('img');
    img.onload = async () => {
        // Load Face-API.js model
        const model = await faceLandmarksDetection.load(
            faceLandmarksDetection.SupportedPackages.mediapipeFacemesh
        );

        // Detect faces in the image
        const predictions = await model.estimateFaces({
            input: img,
        });

        // Check if at least one face is detected
        if (predictions.length > 0) {
            alert("has face.");
            // Proceed with form submission or further processing
        } else {
            alert("No Face");
            // Optionally, reset the photo input field to allow re-capturing the selfie
            document.getElementById('take-photo').value = '';
        }
    };
    img.src = URL.createObjectURL(input.files[0]);
    }
 }


// Function to handle photo preview
function previewPhoto(input) {
var preview = document.getElementById('photo-preview');
if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
        preview.src = e.target.result;
        preview.style.display = 'block';
        validateSelfie(input); // Call the function to validate the selfie

    }
    reader.readAsDataURL(input.files[0]);
  } else {
    preview.src = '#';
    preview.style.display = 'none';
   }
} 

Is there a way to unwrap response when using trpc express adapter?

I have been using trpc [enter link description here][1]
And what I have seen is it always wraps the response inside result.data object. so all endpoints respond with

{result : {data:{ original_response : []} }

Is there a way to unwrap the result, and respond with original result? And is it possible to do this for a specific endpoint alone?

Went through its documentation and some other resources, but couldnt find any lead. any help or tip appreciated.

‘popstate’ event not firing when clicking back button in Chrome

I have something like a single page web application. To handle a back button click from the user I use the ‘popstate’ event:

I have something like a single page web application. To handle a back button click from the user I use the ‘popstate’ event:

In Firefox and Safari, the event works normally – instead of going to the previous page (login page), navigation inside the application occurs.

In Chrome, after the latest updates, the event is correctly called only once. If you press the “back” button a second time, the event will not work and the user will be taken to the login window.

Here’s my code:

function removeBack(){
        history.pushState(null, null, '');
        window.addEventListener('popstate', function () {
console.log('backOneStep0') ;       
            backOneStep(0); // return to the previous application screen
            history.pushState(null, null, '');
        });
    };

Note – if you click anywhere on the page before the second click, the event will fire a second time.

UPD. Here – Chrome popstate not firing on Back Button if no user interaction

They say that this is how it should be, but until recently everything worked! How then can you make a single-page application if you can’t catch the back button being pressed?