React with routes deployed with FastApi blocks fastapi endpoints

I’ve a working example of serving create-react-app build with FastApi.

app.mount("/static", StaticFiles(directory="static/static", html=True), name="static")

templates = Jinja2Templates(directory="static")

app.include_router(auth.router)
app.include_router(api.router)


@app.route("/{path:path}")
async def read_root(request: Request, path: str = None):
    return templates.TemplateResponse("index.html", {"request": request})

React app routing is working, and sides that use get methods from backend work as well, but the post method that should return a token does not work and returns 405 error, method not allowed.

i have tried doing things like these:
https://github.com/tiangolo/fastapi/issues/130#issuecomment-491379252
yet this doesn’t help at all.

How to send props to another component at Vue.js when I use addEventListener click?

I have two components, TimeLine.vue(Parent) and SuspendedMemo.vue(Child)

TimeLine.vue(Parent)

<template>
  <SuspendedMemo v-model="isOpenMemo" @approve="updateMemo" :groupsData="groupsData" :selectedShopId="selectedShopId" :itemId="itemId"></SuspendedMemo>
  <UpdateComplete v-model="isOpenUpdateComplete" @updateComplete="updateComplete"></UpdateComplete>
</template>

  watch: {
    optionsData () {
        groupTemplate: (item, element, data) => {

          // Ckick
          i.addEventListener('click', () => {
            const itemId = item.id
            console.log('Timeline of itemId', itemId)
            this.data = item.suspendedReserveMemo
          })

        }
      }
      return _.merge({}, base, this.options)
    }
  },
  data () {
   return {
    itemId: undefined
   } 
  },
</script>

When I click above, I can see value at “itemId” but I don’t know how this value send to child component…

In the SuspendedMemo component, which is a child component, I want to put “itemId” into ${this.itemId} part but the following code doesn’t work….

SuspendedMemo.vue(Child)

  props: {
    itemId: {
      type: Number,
      default: () => {}
    },
  },
  mounted () {
    console.log('SuspendedMemo内のitemId', this.itemId)
  },
console.log('SuspendedMemo内のitemId', this.itemId) is Undefined. Why?

Error while reading data from firestore in expo project

I get this error:

ERROR  [2024-01-21T17:28:49.065Z]  @firebase/firestore: Firestore (10.7.2): INTERNAL UNHANDLED ERROR:  TypeError: Cannot read property 'includes' of undefined 
at isSafari (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:154341:53)
at __PRIVATE_getDefaultRelativeIndexReadCostPerDocument (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:181880:35)
at __PRIVATE_QueryEngine (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:181881:8)
at createLocalStore (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:187375:83)
at ?anon_0_ (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:187355:256)
at next (native)
at asyncGeneratorStep (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:7269:26)
at _next (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:7288:29)
at tryCallOne (/home/expo/workingdir/build/react-native-lab/react-native/packages/react-native/ReactAndroid/hermes-engine/.cxx/MinSizeRel/6q1z5s36/x86_64/lib/InternalBytecode/InternalBytecode.js:53:16)
at anonymous (/home/expo/workingdir/build/react-native-lab/react-native/packages/react-native/ReactAndroid/hermes-engine/.cxx/MinSizeRel/6q1z5s36/x86_64/lib/InternalBytecode/InternalBytecode.js:139:27)
at apply (native)
at anonymous (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:46872:26)
at _callTimer (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:46751:17)
at _callReactNativeMicrotasksPass (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:46796:17)
at callReactNativeMicrotasks (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:47002:44)
at __callReactNativeMicrotasks (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:9343:48)
at anonymous (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:9116:45)
at __guard (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:9315:15)
at flushedQueue (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:9115:21)
at callFunctionReturnFlushedQueue (http://192.168.100.98:8081/node_modules%5Cexpo%5CAppEntry.bundle//&platform=android&dev=true&hot=false&transform.engine=hermes&transform.routerRoot=app:9100:33)

By calling a function like this:

const querySnapshot = async () => {
try {
  const snapshot = await getDocs(collection(db, "sales"));
  snapshot.forEach((doc) => {
    console.log(`${doc.id} => ${doc.data()}`);
  });
} catch (error) {
  console.log(error.message);
}};

I have tried updating firebase and expo in my project but it always ends with the same error.

How to implement azure MSAL/oauth and get access tokens on a fullstack application (reactjs, python flask)?

I need some advice on how to implement microsoft oauth using msal-browser on frontend react and msal for python on a flask backend

The use case for the application is that only logged in users within the same organization tenant can access the application and also need valid tokens to be able to call apis (flask backend)

I have managed to set up and configure everything needed on entra ID(azure active directory) and got a PublicClientApplication instance working on the reactjs frontend, including getting authorization code from the redirect, but now i am stuck on what to do next

i attempted to pass the authorization code directly to my backend through calling an api endpoint on the flask application, which then next uses a ConfidentialClientApplication and acquire_token_by_authorization_code method to attempt getting access token, but I get the following error:"AADSTS50148: The code_verifier does not match the code_challenge supplied in the authorization request for PKCE"
looking at the documentation doesn’t tell me anything about how i should be resolving this issue and if i am even implementing this correctly

i took a look at the documentation for other methods in ConfidentialClientApplication and saw the method acquire_token_on_behalf_of see: https://msal-python.readthedocs.io/en/latest/#msal.ConfidentialClientApplication and i am wondering if i should be using this method instead

I am new to oauth/PCKE/authorization code flow so any advice would be greatly appreciated, thank you!

msal config on reactJS(using msal-browser):

export const msalConfig = {
    auth: {
        clientId: clientId,
        authority: authority,
        redirectUri: "/auth",
        postLogoutRedirectUri: "/",
    },
    cache: {
        cacheLocation: "sessionStorage",
        storeAuthStateInCookie: isIE || isEdge || isFirefox
    }
};

flask:

@app.route("/getAToken", methods=["GET","POST"])
def authorized():
    #get code from POST json body
    req_body = request.get_json()
    code = req_body["code"]
    #intialize empty result
    result = None
    #get access token
    if code:
        result=azure.acquire_token_by_authorization_code(
            code,
            scopes=["User.Read"],
            redirect_uri="http://localhost:5173/auth",
            )

on App registrations my redirect URI is configured as http://localhost:5173/auth for SPA application

How detect DuckDuckGo browser in Javascript or backend?

How can I detect that a user is using the DuckDuckGo browser?

I have a page that links to the appropriate browser extension store. I need to detect the DuckDuckGo browser so I can display a message saying that the extension can’t be added.

Currently the user is directed to the store of whatever browser DuckDuckGo is spoofing as, currently Edge on Windows. (Meaning that they use the same user agent as Edge.)

Note that Brave also spoofs as another browser, but they added a way to detect it: window.navigator.brave

creating a function to loop values through an array to return a boolean if there is a value found in the array between the two chosen values

I’ve been working on this problem for so long i feel I’ve gone off the deepend and completly corrupted my way of thinking about the problem any help is appreciated thank you !!

instruction:

Create a function that works as follows:

  • The function name is ‘doesArrayIncludeItemsBetweenVals’
  • given an array of numbers. You can use it as the arr for testing purposes
  • The function take an arr (array), val1 (number) and val2 (number) as arguments.
  • The function returns a boolean if array includes an item that is greater than val1 and less than val2
  • The function MUST have 2 return statements: make an early return if the item is found and use the default return otherwise
  • The function MUST be written with NAMED function syntax.
  • doesArrayIncludeItemsBetweenVals([2, 4, 2], 3, 5) => true
  • doesArrayIncludeItemsBetweenVals([2, 4, 2], 5, 10) => false

my answer so far :

function doesArrayIncludeItemsBetweenVals(arr,val1,val2){
if (val1 < arr.length || val2 > arr.length){
for (let element = 0; element < arr.length; element++){
  if ( element > val1 && element < val2){
    return true
   } else return false
   }
  }
   console.log(doesArrayIncludeItemsBetweenVals([2,4,2],3,5))
 }

I tried to make a loop that was in the fuction to be executed so that when you set your parameters to be processed through the function it would output weather there was a value within the array that was also between the to choses values (val1 and val2) so far i’m achieving the exact opposite of what i’m trying to and its still not returning the desired boolean. I cant find an example of how to correctly apply the loop in a function any help is GREATLY appreciated

Does createElement() trigger a reflow before the element is appended to the DOM? Confusing abt DocumentFragment behavior

I’m trying to figure out when exactly a reflow or repaint is triggered when an element is created.

The context for this is trying to understand if a DocumentFragment is necessary if the elements are not appended to extant items in the DOM tree until the end of the function. Here’s an example:

HTML:

<body>
   <div id=target> </div>
</body>

JS:

const ul = document.CreateElement("ul")

for (let i=0; i<100000; i++) {

   let li = document.CreateElement("li")
   let li_text = document.CreateTextNode("Node #: " + i)

   li.appendChild(li_text)
   ul.appendChild(li)

}

document.getElementById("target").appendChild(ul)

In this example, is a reflow triggered every time an <li> is created in the loop? Or is only one reflow triggered after the <ul> is appended to <div id=target>?

If it’s the former, would the appropriate way to prevent this multiple-reflowing be: (1) creating a document fragment, (2) appending a <ul> child to the fragment, (3) getting that <ul> and appending the <li> to it, then (4) appending the fragment to the <div>?

If it’s the later… then what’s the advantage of using a document fragment in contexts like this?

Context

I’m working on project which involves dynamically creating many lists — I’m working on performance optimization, and am unsure how to monitor or test for this kind of behavior. Typically I test on Firefox, with apache hosting from a local directory.

How to make outbound call from the phone? Twilio

My case is next:
I have an app where I receive all calls recordings from Twilio, and do some operations using AI and other tools on it.
I also need to handle outbound calls, for now only inbound are present in Twilio, because outbound calls are done directly without Twilio as intermediary.

So, I have created the React Native mobile app, where I expect to type a phone number of some person and call to her, and I want to receive recording of that call in Twilo. How can I solve it?

Flow is next:

  • Me, PhoneNumber1
  • Person, PhoneNumber2,
  • Twilio, PhoneNumber3 (purchased number)

Expected flow:
I send request to API from mobile app with from=PhoneNumber1, to=PhoneNumber3 and using Twilio I connect that two phones, I think it’s similar to conversations, but I am not sure that it’s the most effective solution.

What do you think can help solve me that?

Module not found: Error: Can’t resolve ‘fs’ in ‘/usr/src/app/node_modules/jpeg-exif/lib’

When building a react app on production getting Error Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Node Version
Node version 18

Running command in Docker Production
npm install --legacy-peer-deps
npm run build

package.json file

"name": "dcts-client",
"version": "0.1.0",
"private": true,
"homepage": "ecommerce",
"dependencies": {
"@emotion/react": "^11.10.0",
"@emotion/styled": "^11.10.0",
"@fortawesome/fontawesome-svg-core": "^6.1.2",
"@fortawesome/free-brands-svg-icons": "^6.1.2",
"@fortawesome/free-solid-svg-icons": "^6.1.2",
"@fortawesome/react-fontawesome": "^0.2.0",
"@hookform/error-message": "^2.0.0",
"@mui/icons-material": "^5.11.0",
"@mui/material": "^5.10.2",
"@mui/x-date-pickers": "^5.0.0",
"@react-pdf/renderer": "^3.0.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"bootstrap": "^5.2.0",
"card-validator": "^8.1.1",
"cross-domain-storage": "^2.0.7",
"dayjs": "^1.11.5",
"env-cmd": "^10.1.0",
"js-cookie": "^3.0.1",
"lodash.isequal": "^4.5.0",
"payment": "^2.4.6",
"query-string": "^7.1.1",
"react": "^18.2.0",
"react-bootstrap": "^2.5.0",
"react-confirm-alert": "^3.0.6",
"react-credit-cards": "^0.8.3",
"react-csv": "^2.2.2",
"react-data-table-component": "^7.5.3",
"react-datepicker": "^4.8.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.36.1",
"react-input-range": "^1.3.0",
"react-medium-image-zoom": "^5.0.2",
"react-phone-input-2": "^2.15.1",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"react-select": "^5.5.9",
"react-slick": "^0.29.0",
"react-to-print": "^2.14.8",
"react-toastify": "^9.0.8",
"simplebar-react": "^2.4.1",
"slick-carousel": "^1.8.1",
"styled-components": "^5.3.6",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "set PORT=3000 && react-scripts start",
"build": "react-scripts build",
"build:production": "set REACT_APP_API_ENDPOINT_BASE_URL=/api && set REACT_APP_API_ENDPOINT_REDIRECT_URL=http://alb-dct-prd-1561780064.us-east-2.elb.amazonaws.com/ && react-scripts build",
"build:testing": "export REACT_APP_API_ENDPOINT_BASE_URL=/api REACT_APP_API_ENDPOINT_REDIRECT_URL=http://dctalb-1569668697.us-east-2.elb.amazonaws.com/ && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

docker File


WORKDIR /usr/src/app/ecommerce

ARG PAYTRACE_URL

ARG REDIRECT_URL

COPY ./DCT-ECOMMERCE/package.json ./

RUN npm install --legacy-peer-deps

COPY ./DCT-ECOMMERCE .

RUN sed -i "s/protect.sandbox.paytrace.com/${PAYTRACE_URL}/g" /usr/src/app/ecommerce/public/index.html

RUN export REACT_APP_API_ENDPOINT_BASE_URL=/ecomm-api REACT_APP_API_ENDPOINT_REDIRECT_URL=${REDIRECT_URL} && npm run build -- --profile

FROM nginx:1.24.0-alpine

COPY ./ngnix/nginx-default.conf.template /etc/nginx/conf.d/default.conf.template
COPY --from=build-ecommerce /usr/src/app/ecommerce/build/ /usr/share/nginx/html/ecommerce

COPY ./docker-entrypoint.sh /

RUN chmod +x /docker-entrypoint.sh

ENTRYPOINT ["/docker-entrypoint.sh"]

CMD ["nginx", "-g", "daemon off;"]

EXPOSE 80 

Unexpected behavior

enter image description here

TypeORM QueryBuilder Limit Join to One Record

The following query gets all clients and their associated products. It also joins each product’s ProductSnapshot which contains historical closing inventories for each product. I want to limit the ProductSnapshot join to one record which could be accomplished by ordering by id 'DESC' and limiting to one record per product. What’s the best way to achieve this?

async findClientsProducts() {
  return await this.clientsRepository
    .createQueryBuilder('client')
    .leftJoinAndSelect('client.products', 'product')
    .leftJoinAndSelect('product.productSnapshots', 'productSnapshot')
    .getMany();
}

How to create a monorepo using yarn that contains multiple apps that can only use the root workspaces?

I have the following folder structure that I want to make a monorepo using yarn:

/root
 /apps
   /app-one
   /app-two
 /packages
   /ui

I want that only the root/packages/* modules can be used by apps/* projects. Meaning I don’t want that apps/app-one can use a module of apps/app-two. root/apps/* can only use modules from root/packages/*,
So I don’t want that root/node_modules can possibly contain any module exported from root/apps/*.

The problem is when I do yarn install inside root/apps/app-one I get the following error:
Problem

I understand that yarn couldn’t link that packages to any remote node module or local module using symlink. But how to achieve what I want If it does not support that ?

What I did:
I initialized yarn using yarn init inside the root/ folder. I updated the root package.json to the following:

{
  "private": true,
  "name": "test",
  "version": "1.0.0",
  "packageManager": "[email protected]",
  "workspaces": [
    "packages/*"
  ]
}

In root/packages/ui/:
1- I did yarn init
2- I created a index.js file with this content: export const A = 22;
3- I changed the package.json to:

{
  "name": "ui",
  "version": "1.0.0",
  "packageManager": "[email protected]"
}

In root/apps/app-one:
1- I did yarn init
2- I changed the package.json to:

{
  "name": "app-one",
  "packageManager": "[email protected]",
  "dependencies": {
    "ui": "*"
  }
}

3- I created a index.js file with this content: import {A} from 'ui'
4- Following the error message after doing yarn install i added an empty yarn.lock file for this to be treated as a seperate project.
error

Also for the modules to be installed in node_modules I added the following .yarnrc.yml file inside root/ and root/apps/app-one: nodeLinker: "node_modules"

This is the final folder structure:
folder structure

Dynamically add blob data to MediaSource and display on video element

The client receives Blobs of data, which represent a certain part of the stream that needs to be display (frame, group of frames, etc). The client mediaplayer should display the received data without waiting for the stream to complete. In a bit of a toy example of the intended goal we have the code:


const remoteVideo = document.getElementById('videoPlayer');
const mediaSource = new MediaSource();
    
remoteVideo.src = URL.createObjectURL(mediaSource);
let sourceBuffer = undefined

mediaSource.addEventListener('sourceopen', ()=>{
  sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64000d,mp4a.40.2"');
    
});





if(navigator.mediaDevices != undefined){
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
    .then(stream => {
      // remoteVideo.srcObject = stream; -> I am aware this works
      var recorder = new MediaRecorder(stream);

      recorder.ondataavailable = event => {
        if(sourceBuffer != undefined){
          event.data.arrayBuffer().then((ret) => {
            // DO WHAT WITH THIS DATA?        
          })
                              
        }
      };

      recorder.start(1000); // every t ms save stream
    
    })
    .catch(error => {
      console.error('Error accessing media devices:', error);
    });
}

Obviously, if there was a disinct end time, I could call the end of stream function and play what is stored in the buffer. But this is not the intended use. I would like to display the Blobs before they have all arrived. Setting the source as the video stream works fine, but these blobs will be received over socket connection.

HTML:

<!DOCTYPE html>
<html lang="en">

    <body>
        <video id="videoPlayer" width="50%" controls muted="muted" autoplay>
            
        </video>
    </body>
    
    <script src="view.js"></script>
</html>

How export json file in JS?

I’m playing around with the SNCF API and I’m having a problem with a json file. Basically I use it to list all the stations, so I imported it with

let stationInput = document.getElementById("search");
let stationList = document.getElementById("station_list");
let stationSearch = stations.libelle;
import stations from '../stations.json';

stationInput.addEventListener('input',function() {
    let searchTerm = stationInput.value.toLowerCase();

    // Filtre des gares avec le terme de recherche
    let filterStation = stationSearch.filter(station => station.toLowerCase().startsWith(searchTerm));

    // Mettre à jour la liste
    updateStationSuggestions(filterStation);
});

function updateStationSuggestions(suggestions){
    stationList.innerHTML = '';

    suggestions.forEach(station => {
        let option = document.createElement('option');
        option.value = station;
        stationList.appendChild(option);
    });
}

but I got this error

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.

I tried to import it from another blank file but still the same error.
What I ultimately want is to be able to list all the stations in order to give them in a search bar

Removing pseudo element based user interaction

How does one use the user’s interaction with an html element to remove a pseudo element? I have an element with a pseudo element, which has 50% width and absolutely positioned. I would like to remove the pseudo element permanently once its parent has been interacted with by the user.

.test {
  position: relative;
  background: blue;
}

.test::before {
  content: "some text";
  background: red;
  width: 50%;
  position: absolute;
}
<div class="test">Lorem ipsum dolor sit.</div>

Using :hover, :active and :focus on the parent doesn’t work. Thanks.

How to have multiple pages/layouts under the same endpoint in Svelte?

I will preface this question by stating I am not a frontend developer.

I am developing a pet project, where I have a form, and when the form is submitted, the user advances to the next “stage”.

For example, a user fills in some basic info, uploads a file, and then in the next page I render the info that the user filled in. I would like all of this to happen under the /app endpoint.

How does this look like in practice? What’s the proper way of developing a page that has multiple “pages” so to say? What are the appropriate terms so I can google more about this?

Right now I have something that looks like this, but I really dislike it.

<script>
  let currentStep = 0;
  let maxSteps = 3;

  function handleNextStep() {
    if (currentStep < maxSteps) {
      currentStep++;
    }
  }

</script>

{#if currentStep === 0}
  <Form nextStep={handleNextStep} />
{:else if currentStep === 1}
  <Render nextStep={handleNextStep} />
{:else if currentStep === 2}
  <App />
{/if}

The problem with this is that if I refresh the page I will lose the “progress”, and overall it doesn’t look good I think.