Cookie not set in request headers in React Js

I have created a cookie using the JS-Cookie package and it is saved in my browser, but the cookie is not set in my request header and is not sent to the server.

I use Axios.

My cookie example:

Cookies.set("myCookie", JSON.stringify(myData), {
      expires: 2,
      sameSite: "none",
      secure: true,
    });

Example of my Axios code:


axios.get("mayUrl", {
    withCredentials: true,
    headers: {   
      "Access-Control-Allow-Origin": "myBackendUrl",
      "Access-Control-Allow-Headers": "*",
      "Access-Control-Expose-Headers": "*",
    },
  
  });
};

I can send a cookie to React from the backend, but when I create a cookie in React, I can’t send it to the backend. It seems that the browser ignores my cookie.

Thank you to those who help me

Prevent click when dragging

Im using Three.js to display a 3d model which users can drag the camera around and click objects to zoom in on them. The issue I’m having is that when you click and drag it reads it as a click and triggers the animation, I need to prevent clicking when dragging, so clicks are only registered when it is just a click and no mouse movement.

function onClick(event) {
    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children, true );

    if ( intersects.length > 0 && intersects[0].object.name==="Tree006") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1,
            x: mesh["Tree006"].position.x,
            y: mesh["Tree006"].position.y,
            z: mesh["Tree006"].position.z,
            onUpdate: function() {
                controls.enabled = false;
                camera.lookAt(0,0,0);
            }
        } );
        console.log( 'Intersection:', intersects[ 0 ] );
        
        
    }

    if ( intersects.length > 0 && intersects[0].object.name!=="Tree006") {
        var object = intersects[0].object;
        gsap.to( camera.position, {
            duration: 1, // seconds
            x: 6,
            y: 4,
            z: 6,
            onUpdate: function() {
                controls.enabled = true;
                camera.lookAt( 0,0,0 );
            }
        } );
    }


}

Fail to record and upload wav to Flask from JS: KeyError: ‘audio_file.wav’

I am trying to record audio via webbrowser for 6 seconds and send it to flask. The audio file then gets converted into a Spectogramm. Afterwards it should be transformed into a Numpy Array to be processed for a model.

But i think that is not the topic of this question here.

I tried several different versions and options but cannot manage.

This is JS code:

function lDUp(){
    var formData = new FormData();

    const startButton = document.getElementById("startLungBtn");
    startButton.addEventListener("click", function() {
      if (!navigator.mediaDevices) {
        console.error("getUserMedia not supported.")
        return;
      }
  
    const constraints = { audio: true };
    navigator.mediaDevices.getUserMedia(constraints)
    .then(function(stream) {
        var chunks = [];
        const recorder = new MediaRecorder(stream);
        recorder.ondataavailable = event => {
            // Collect all the chunks of the recording in an array.
            chunks.push(event.data);
        };

        const audioContext = new AudioContext();
        const audioStreamSource = audioContext.createMediaStreamSource(stream);
        

        recorder.onstop = event => {
            console.log("Recording stopped.")
            // Create a blob with all the chunks of the recording.
            let blob = new Blob(chunks, { type: "audio/wav" }); 

            // let blob = new Blob(chunks, { type: recorder.mimeType }); 
            chunks = [];
            startButton.disabled = false;
  
            // Create form data that contain the recording.
            formData.append("audio_file", blob, "audio_file.wav");


            

          };
        recorder.onstart = event => {
            console.log("Recording started.");
            startButton.disabled = true;
            // Stop recording when the time is up.
            setTimeout(function() { recorder.stop(); }, 6000);
            $.ajax({
                
                type: "POST",
                url: "http://127.0.0.1:5000/LungUploader",
                processData: false,
                contentType: false,
                cache: false,
                data: formData,
                success: function(response) {
                console.log(response);
                console.log("This is class: ", response)
                },
                error: function(err) {
                    console.log(err);
                    }
            }); 
                        
        };
        recorder.start();
    })
    .catch(function(err) {
          console.error(err);
      });
    });
        
                  
                
}

This is code for flask:

@app.route('/LUploader', methods=["GET", 'POST'])
def lUploader():

    if request.method == "POST":

        f = request.files["audio_file.wav"]
        with open('audio.wav', 'wb') as audio:
            f.save(audio)


        print("Checkpoint1")
        y, sr = lb.load(f)

        print("Checkpoint")
        #Plot signal in
        plt.figure(figsize=(10,3))
        src_ft = lb.stft(y)
        src_db = lb.amplitude_to_db(abs(src_ft))
        specshow(src_db, sr=sr, x_axis='time', y_axis='hz')  
        plt.ylim(0, 5000)        
        plt.close()
}

Thanks for help in advance ๐Ÿ™‚

What do round brackets mean here? React Hook Form

Here is a custom input component

const Input = ({props}) => {
    return (
        <input type="text" {...props} {...props.reg}/>
    );
};

I passed a React Hook Form register function to this custom Input.

        <Input props={{
            placeholder: 'Name',
            id: 'form__name',
            name: 'name',
            reg: {...(register('name'), {required: true})}
        }}/>

Input was registered and I was not able to figure out what do round brackets before the spread operator mean.

What kind of JS/React syntax is it? …(xxx, xxx)

P.S. this line of code

reg: {...(register('name'), {required: true})}

was taken from some youtube video, I just rewrote it, but round brackets before spread operator were still used in the video

Why does my minimax algorithm not block certain diagonal moves?

I’ve almost completed the logic for my minimax and its working quite well. But i’m still finding a few diagonal moves where the AI is seemingly getting it wrong. For example if you play square 3,5,6 and 7 you will win. It doesn’t block the bottom corner for some reason.

Here’s the minimax call recursively getting the best score that our computer can make:

          let compMove;
          let bestScore = -Infinity;
          for (let i = 0; i < 9; i++) {
            if (gameBoard.array[i] == '') {
              gameBoard.array[i] = 'X';
              let score = minimax(gameBoard.array, 0, true);
              gameBoard.array[i] = '';
              if (score > bestScore) {
                bestScore = score;
                compMove = i;
              }
            }
          }

Here is the actual minimax function itself:

          let scores = {
            X: 10,
            O: -10,
            tie: 0
          }
          
          const minimax = (board, depth, maximizingPlayer) => {
            let result = checkWinner(gameBoard.currentPlayer);
            
            if (result !== null) {
              return scores[result];
            }
            
            if (maximizingPlayer) {
              let bestScore = -Infinity;
              for (let i = 0; i < 9; i++) {
              
                if (board[i] == '') {
                  board[i] = 'O';
                  let score = minimax(board, depth + 1, true);
                  board[i] = '';
                  if (score > bestScore) {
                    bestScore = score;
                  }
                }
              }
              return bestScore;

            } else {
                let bestScore = Infinity;
                for (let i = 0; i < 9; i++) {
                  if (board[i] == '') {
                    board[i] = 'X';
                    let score = minimax(board, depth + 1, false);
                    board[i] = '';
                    if (score < bestScore) {
                      bestScore = score;
                    }
                  }
                }
    
                return bestScore;
            }
          }

If anything sticks out to anyone I’d greatly appreciate it. I’m stumped!

If you’d like to test the current state of the game here’s the codepen:

https://codepen.io/itswakana/pen/gOeMrym?editors=1111

AWS SDK for Node, Cognito Pool – can’t trigger forgot password – “Missing required key ‘Username’ in params”

I have a Node.js backend that contains different routes interacting with AWS Cognito using AWS SDK for Node.js

All my routes work except the one that calls forgotPassword API. For some reason, it doesn’t read the username parameter. The request seems to have succeeded, in that it returns a Status 200, but the response object contains an error.

{ "message": "Missing required key 'Username' in params", "code": "MissingRequiredParameter", "time": "2022-07-15T10:50:57.297Z" }

My code below. The first is the route, it calls a function contained in the “controller” folder.

router.post("/forgotpassword", async (req, res, next) => {
    console.log("Function")
  const userName = req.body.userName;

  const response = await triggerForgotPassword({
    userName: userName
  });

  res.json(response);
});

export const triggerForgotPassword = async (userData) => {
    const userName = userData.userName;

    const params = {
        ClientId: process.env.CLIENT_ID,
        Username: userName,
      };
  
      try {
        const response = await cognitoidentityserviceprovider
          .forgotPassword(params as any)
          .promise();
        return response;
      } catch (error) {
        return error;
      }
};

Not sure what I’ missing. Hope someone can help. Many thanks.

CSS to iframe priority

I’m trying to inject some CSS into an iFrame, and it works fine, except there is a delay before the new CSS takes effect. How can I set priority for iframe CSS?
I use this code for the iframe section:

<iframe id="myiFrame" fetchpriority="low" loading="lazy" width="1024px" height="200px" src="mypage.html"></iframe>

And use this code for styling:

<script>
window.onload = function() {
  let frameElement = document.getElementById("myiFrame");
  let doc = frameElement.contentDocument;
  doc.body.innerHTML = doc.body.innerHTML + '<style>.jeg_header_wrapper{display:none!important}</style>';
}
</script>

Javascript HTML MIDI tool for piano videos

I want to create a midi tool with multiple features, but there is this one feature that I don’t know how I am gonna go by doing. I have the interface down: https://i.stack.imgur.com/j9P8D.png
Website: https://misztamusique.com/midi-tools

Essentially I want to make a loop in javascript where depending on how many colors you want that it will loop between midi-channels and check every note one by one and set it to a different midi channel. So if you select 2 colors, it will only have 2 channels to choose by, but if you choose 3 colors it will have 3 channels to chose from. So the first note will be 1, second, 2 and third 3 and then it loops. 123 123 123 you get the point.

I want to make it so that you import a midi file to the website and submit it that the javascript automatically does it so that you can download it.

So now the question, how am I gonna do this in html and js and how am I gonna add javascript libraries and what libraries should I use? It would also be helpful to get some code on how I would do it.

CEF – how to get a variable from JS to ะก++

Please help me, I’ve been suffering for two weeks, I can’t understand if it’s possible in CEF to get the value of a variable from the JS code to a C++ variable?

For example:

I am executing js code in a browser window using the method CefFrame::ExecuteJavaScript:

(*frame).GetMainFrame()).ExecuteJavaScript("const elem = document.getElementsByClassName("my_class")[0];const rect = elem.getBoundingClientRect(); alert(rect.x + ":" + rect.y)", "", 1);

And everything works great, but only “inside” javascript.

Here’s the question: is it possible to somehow get the value of a variable to a rect.x to pull out and put in a C++ variable int rect_x ?

unable to pass data between one component to another component in angular

I am trying to pass data from one component to another component I used the service file method.
I created two components one is login and the second is home. I have to pass data from login to home.
in the login component, I take user input, and the home component should print that.
I used this code below, but when I give input, it is not printing in output.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  message : any;

  constructor() { }
  setMessage(data: any){
    this.message=data;
  }
  getMessage(){
    return this.message;
  }
}

this is my home component code

import { Component, OnInit } from '@angular/core';

import { SharedService } from '../shared/shared.service'

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
 message : string | undefined;

  constructor(private shared:SharedService ) {}
  ngOnInit() {
   this.message =this.shared.getMessage()
} 
}
<h1> {{ message }} </h1>

this is my login component code

import { Component, OnInit } from '@angular/core'
import { SharedService } from "../shared/shared.service"

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  message : any ;

  constructor(
    private  shared: SharedService
  ) { }
  
  ngOnInit(): void {
    this.shared.setMessage(this.message)
  }

}
    <input required type="text" class="form-control" placeholder="Enter username" [(ngModel)]="message">

Hi I tried to implement facelandmark detection using mediapipe

But the problem is I want to get rid of the video and show only the landmark points sepearately. I tried to create a new canvas to do the same but somethings wrong. I’m fairly new to JS and react so could you please help me out.

The code:
const detect = async (net) => {
if (
typeof webcamRef.current !== “undefined” &&
webcamRef.current !== null &&
webcamRef.current.video.readyState === 4
) {
// Get Video Properties
const video = webcamRef.current.video;
const videoWidth = webcamRef.current.video.videoWidth;
const videoHeight = webcamRef.current.video.videoHeight;

  // Set video width
  webcamRef.current.video.width = videoWidth;
  webcamRef.current.video.height = videoHeight;

  // Make Detections
  // OLD MODEL
  //       const face = await net.estimateFaces(video);
  // NEW MODEL
  const face = await net.estimateFaces({input:video});
  console.log(face);

  // Get canvas context
  const ctx = canvasRef.current.getContext("2d");
  const ctx1 = canvasRef1.current.getContext("2d");
  



  requestAnimationFrame(()=>{drawMesh(face,ctx,ctx1)});
}

};

useEffect(()=>{runFacemesh()}, []);

return (

<div className="App">
  <header className="App-header">
    <Webcam
      ref={webcamRef}
      style={{
        position: "absolute",
        marginLeft: "auto",
        marginRight: "auto",
        left: 0,
        right: 0,
        textAlign: "center",
        zindex: 9,
        width: 1000,
        height: 1000,
        display: "flex"
        
      }}
    />

    <canvas
      ref={canvasRef}
      style={{
        position: "absolute",
        marginLeft: "auto",
        marginRight: "auto",
        left: 0,
        right: 0,
        textAlign: "center",
        zindex: 9,
        width: 640,
        height: 480,
        flex: 1
      }}

      
    />

    <canvas
      ref={canvasRef1}
      style={{
        position: "absolute",
        marginLeft: "auto",
        marginRight: "auto",
        left: 0,
        right: 0,
        textAlign: "center",
        zindex: 9,
        width: 640,
        height: 480,
        flex:1
      }}
      
      
    />

  </header>
</div>

);
}

Javascript data attribute array [duplicate]

I have a data attribute of an input that’s an array but it doesn’t but when I try and use it it’s not an array but a string. I would like to use as an array.

<input id='myId' type="text" title="Search" data-options='["some", "string", "here"]' />

But when I do this

const options = document.getElementById('myId').dataset.options;
    for (i = 0; i < options.length; i++) {
        console.log(options[i]);
    }
<input id="myId" type="text" title="Search" data-options='["some", "string", "here"]' />

Instead of getting some string here I’m getting the letters