what is the equivalent of python open(filepath, ‘rb’) in JavaScript

I can open the file in binary mode with Python and store it in a variable.
I have been researching this for two days, and I can’t seem to find a straightforward answer. I need this because I have been working on a project that we have completed in Python, but we need to convert it into JavaScript. The issue that I’m having is that I need to send a file through an API call. Still, every time I do, I get this error ‘ HTTP 415 Unsupported Media TypeThe provided media type is not supported for the requested URI. What I have is a JSON file that I need to pass to a post-call in binary

files = {'file': open(JSON_File, 'rb')}
response = requests.post(
    URL, 
    auth=(USERNAME, PASSWORD),
    files=files
    #files=files, verify = False
)

response.text

how can I do this in nodeJS? I completed the above already in Python.

How to store response data into an array out of the current function in node js?

How do i store all result data into pImages array i am getting the result but in that case i think async function will work but i dont know how to apply it. please help, my code is

exports.addImage = (req, res, next) => {
    let imageArray = req.files.productImageArray;

    if (!req.files || Object.keys(req.files).length === 0) {
        return res.status(400).send("No files were uploaded.");
    }
    
    // here all images will be stored in array format
        let pImages = [];

         for (let f in imageArray) {
            imagekit.upload(
                {
                    file: imageArray[f].data, //required
                    fileName: imageArray[f].name, //required
                    customMetadata: {
                        color: req.body.productLabels[f],
                        default: req.body.defaultProduct[f]
                    }
                },
                function(error, result) {
                    if (error) console.log(error);
                    else {
                        console.log(result)
                        pImages.push(result)
                    }
                }
            );
        }

    console.log("p", pImages); //output p []
   
};

Thanks in Advance

h2 field not updating with values

I am trying to update the h2 field in index.html with the ID “summary” with the values inside of index.html (refer to line 87 in there, that is where I am having a problem).

I want the text that says “test” to change to a string with those four variables.

For context, this application is a health risk calculator for a class assignment that is supposed to calculate your supposed health risk based on BMI, blood pressure, family history, and age. We are supposed to have the calculations run on server side for the purposes of the assignment, which I have implemented successfully. However, I need to provide a summary of the values used in the calculation, which is for some reason, giving me a major headache. I thought this would be an easy fix but I am obviously missing something stupid.

Let me know what I am missing please.

HTML:

<h2 id="summary">test</h2>

In JavaScript file in an app.get block that is called from HTML vvv

document.getElementById("summary").innerHTML =  ("(Age Risk: " + ageNum + ", Family History Risk: " + famHistNum + ", BMI Risk: " + bmiNum + "Blood Risk: " + bloodRisk);

Fetch data from db into a HTML form

I’m new to PHP and SQL, so I’m doing a booking form. So far it POST’s into a database but the only thing missing is to show the available dates and hours for the appointments in the selector at the beginning of the form, and for those dates to be unselectable once booked by other user. I’ve already tried to do it by XMLHttpRequest but i haven’t been able to make it work.

I’ve already create a table in the DB in which the available dates are stored, this is the structure. When the date-time it’s available the state is 1, otherwise is 0.

https://drive.google.com/file/d/1ZqYAA-JZy0ed87KNuMzN7B326jhYuw3V/view?usp=sharing

This is my HTML form

<form class="needs-validation col-sm-11 col-md-6 col-lg-6 col-xl-6" style="border: solid black; padding:10px; border-radius: 5px; border-width: 1.5px; box-shadow: 5px 5px 5px rgb(0 0 0 / 0.2);" novalidate>


  <label for="exampleFormControlInput1" style="color:#9eb33e;"><b>Fecha y hora en que desea la charla</b></label>
  <div class="row">
    <div class="col-sm-6">
      <label for="exampleFormControlSelect2">Selecciona la fecha charla</label>
      <select multiple class="form-control" id="exampleFormControlSelect2" name="fecha">
        <option disabled="true"><b>--MARZO--</b></option>
        <option>2022-03-24</option>
        <option>2022-03-25</option>
        <option disabled="true"><b>--ABRIL--</b></option>

      </select>
    </div>
    <div class="col-sm-6">
      <label for="exampleFormControlSelect2">Selecciona hora de la charla</label>
      <select multiple class="form-control" id="exampleFormControlSelect2" name="hora">
        <option disabled="true"><b>--MARZO--</b></option>
        <option></option>
        <option>00:00:00</option>
        <option>12:00:00</option>
        <option disabled="true"><b>--ABRIL--</b></option>

      </select>
    </div>

  </div>

  <label for="exampleFormControlInput1" style="color:#9eb33e;"><b>Datos de la persona encargada</b></label>

  <div class="row">

    <div class="col-sm-6">
      <label for="exampleFormControlInput1">Nombres</label>
      <input type="text" class="form-control" placeholder="" name="nombre" required>
      <div class="invalid-feedback">
        Por favor escriba los nombres de la persona encargada
      </div>

    </div>


    <div class="col-sm-6">
      <label for="exampleFormControlInput1">Apellidos</label>
      <input type="text" class="form-control" placeholder="" name="apellido" required>
      <div class="invalid-feedback">
        Por favor escriba los apellidos de la persona encargada
      </div>
    </div>



  </div>

  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <label for="exampleFormControlInput1">Correo electrónico</label>
        <input type="email" class="form-control" name="email" placeholder="[email protected]" required>
        <div class="invalid-feedback">
          Por favor provea un correo electrónico valido
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <label for="exampleFormControlInput1">Número de contacto</label>
        <input type="text" class="form-control" name="numero" placeholder="+57 --- --- ----" required>
        <div class="invalid-feedback">
          Por favor provea un número de contacto (Celular o fijo)
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <label for="exampleFormControlInput1">Nombre del colegio</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" name="colegio" required>
        <div class="invalid-feedback">
          Por favor escriba el nombre del colegio al que representa
        </div>
      </div>
    </div>
  </div>


  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <label for="exampleFormControlInput1">Número aproxmado de estudiantes</label>
        <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="" name="numest" required>
        <div class="invalid-feedback">
          Por favor provea un número de estudiantes aproximados a asistir
        </div>
      </div>
    </div>
  </div>

  <div class="row">
    <div class="col-sm-12">
      <div class="form-group">
        <input type="checkbox" class="custom-control-input" id="customControlAutosizing" required>
        <label class="custom-control-label" for="customControlAutosizing" style="margin-left:15px;">Acepto
                        la política de tratamiento de datos</label>

        <div class="invalid-feedback">
          Es necesario aceptar la política de tratamiento de datos
        </div>
      </div>
    </div>
  </div>


  <div class="button-area">
    <button type="submit" class="btn btn-primary col-sm-12" style="background:#9eb33e; border-color:#9eb33e;">Enviar</button>
  </div>

</form>

This is the JS code

const form = document.querySelector("form"),
statusTxt = form.querySelector(".button-area");

form.onsubmit = (e)=>{
    e.preventDefault()
    
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "public/php/registro.php",true);
    xhr.onload = ()=>{
        if(xhr.readyState == 4 && xhr.status == 200){
            let response = xhr.response;
            console.log(response);
        }
    }
    let formData = new FormData(form);
    xhr.send(formData);
 }
 

And this is the PHP that controls it


include_once 'conect_db.php';


$fecha = $_POST['fecha'];
$hora = $_POST['hora'];
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$email = $_POST['email'];
$numero = $_POST['numero'];
$colegio = $_POST['colegio'];
$numest = $_POST['numest'];


if(!empty($fecha) && !empty($nombre) && !empty($apellido) && !empty($email) && !empty($numero) && !empty($colegio) && !empty($numest)){
$reciever = "[email protected]";
    $subject = "Mensaje de $nombre: Nueva cita UNaspirante.";
    $body = "Datos de la persona encargada:/n Nombre:$nombre/n Apellido:$apellido/n Correo Electronico:$email/n Numero de contacto:$numero/n Colegio:$colegio/n Numero de estudiantes:$numest/n FECHA:$fecha/n. HORA:$hora/n";
    $sender = "$email";
    
    $consulta = "INSERT INTO UNaspirante_form(nombre, apellido, email, numero, colegio, num_estudiantes, fecha_seleccionada, hora_seleccionada) VALUES ('$nombre','$apellido','$email','$numero','$colegio','$numest','$fecha','$hora')";
    $resultado = mysqli_query($mysqli , $consulta);
    
    
    if($resultado){
        echo "Tu info ha sido enviada";
    }else{
        echo "Tu info NO ha sido enviada";
    }
    
}else{
    echo "no se pudo enviar el mensaje";
}

?>``` 

**Thanks in advance for all the help**


  [1]: https://i.stack.imgur.com/M74PD.png

React useEffect + useState seems to initialize components before state variable defined?

I am trying to attach a JWT token from AWS Cognito to Uppy requests in my upload component. To get the token, I believe I need an async function:

async function getSessionToken() {
  const data = (await Auth.currentSession()).getAccessToken().getJwtToken()
  console.log(data)

  return data;
}

However, I need the value of getSessionToken (ie. the actual token) before I initialize my Uppy component. To do this, I thought it would be best to use useEffect, whereby I could set the state of a variable using useState and render the Uppy component after getSessionToken returned a value:

  const [tokenData, setTokenData] = useState();

  useEffect(() => {
    console.log(tokenData)
    getSessionToken().then((token) => { setTokenData(token) })
  }, []);

  return (
    <>
      {tokenData === 'undefined' ? <Skeleton variant="rectangular" width={210} height={118} />
        : <UppyComponent data={tokenData} />}
    </>
  )

where UppyComponent is:

function UppyComponent(props) {
  console.log(props.data)
  const uppy = useUppy(() => {
    return new Uppy({
      debug: true,
      autoProceed: false,
      restrictions: {
        maxNumberOfFiles: 1,
        minNumberOfFiles: 1,
        allowedFileTypes: ['video/*'],
        requiredMetaFields: ['caption'],
      }
    })
      .use(AwsS3Multipart, {
        limit: 4,
        companionUrl: 'http://localhost:3020/',
        companionHeaders: {
          'Authorization': "Bearer " + props.data,
          'uppy-auth-token': "Bearer " + props.data,
        }
      })
      .use(GoldenRetriever)
      .on('complete', result => {
        console.log('successful files:', result.successful)
        console.log('failed files:', result.failed)
      })
  })

  return <Dashboard
    uppy={uppy}
    plugins={['DropTarget']}
    inline={true}
    target='.DashboardContainer'
    showProgressDetails={true}
    note='Video only, up to 1 MB'
    width='400'
    metaFields={[
      { id: 'name', name: 'Name', placeholder: 'Give your work a title. ' },
      { id: 'caption', name: 'Caption', placeholder: 'describe what the image is about' }
    ]}
    browserBackButtonClose={false}
  />
}

However, I noticed that UppyComponent is still being initialized/rendered before getSessionToken returns. Looking at the requests, I see that props.data is still undefined in UppyComponent. I had thought, since useEffect wouldn’t set the state variable until after getSessionToken returned, props.data wouldn’t set until getSessionToken did as well. Is this not the case?

And is there a workaround?

How to access the display property of a row inside a html table

I have an html table populated by sql, in a php file something like this:

<table id='myTable'>
    <tr> <th>Name</th><th>Weight</th> </tr>
     <tbody id='budy'>
      <tr>
        <td> x </td><td> 3 kg</td>
      </tr>
      <tr>
        <td> y </td><td> 9 kg</td>
      </tr>
      <tr>
        <td> x </td><td> 1 kg</td>
      </tr>
       <tr>
        <td> x </td><td> 6 kg</td>
      </tr>
       <tr>
        <td> y </td><td> 7 kg</td>
      </tr>
      </tbody>
      </table>

And this filter function to search either the name or the weight across the table:

function doSearch() {
    var searchText = document.getElementById('filterInput').value;
    var targetTable = document.getElementById('myTable');
    var btn=document.getElementById("totalbtn");
    var targetTableColCount;
    document.getElementById("totalbtn").disabled=false;
    //Loop through table rows
    for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++ ) {
         var rowData = '';
         //Get column count from header row
          if (rowIndex == 0) {
              targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
              continue; //do not execute further code for header row.
            }
           var rowCells = targetTable.rows.item(rowIndex).cells;
           for (var colIndex = 0; colIndex < 2; colIndex++) {
                var cellText = '';

                if (targetTable.rows.item(rowIndex).cells.item(colIndex)) {                      
                    cellText = rowCells.item(colIndex)[(navigator.appName == 'Microsoft Internet 
                            Explorer')? "innerText" : "textContent"];
                 }
                   rowData += cellText;
            }

             // Make search case insensitive.
            rowData = rowData.toLowerCase();
            searchText = searchText.toLowerCase();

            //If search term is not found in row data
            //then hide the row, else show
            if (rowData.indexOf(searchText) == -1)
                 targetTable.rows.item(rowIndex).style.display = 'none';
              else
                  targetTable.rows.item(rowIndex).style.display = 'table-row';
            }
        }

I understand the function, but i am not the one who programmed it, my question is how can i access just the rows left(which i believe have the html property ‘display!= none’) after the user input text in the text filter? i have tried with:

  function sum(){
      var buttoncal = document.getElementById("totalbtn");
      var table = document.getElementById("myTable");
      var sum=0;
      var temp;
     for(var i=1; i< table.rows.length; i++){
          sum = sum + parseInt(table.rows[i].cells[2].innerHTML.slice(0,1));
          temp=table.rows[i].cells[4].innerHTML.slice(0,1)
          console.log(temp);
      }
    }

but so far i only get the sum of all rows, including the one with the “new” display property of ‘none’ instead of just adding the rows shown after the filter is used.
Thanks for any advice to solve this.

Unit testing for backend and services methods calls with Jasmine

I started working with tests, more specifically with Jasmine, and I’m having some difficulty to test if the backend and some services methods are being called.

So basically I’m calling the forgotPassword method when the formulary is submitted and I was wondering how can I properly check if the API (apiSendPasswordResetLink) and the services methods (showLoader, showAlert and navigateTo) are being called as expected.

async forgotPassword() {
    try {
        console.log("1");
        this.loadingService.showLoader();
        console.log("2");
        await this.userService
            .apiSendPasswordResetLink(this.form.value['email'])
            .toPromise();

        console.log("3");
        this.utilitiesService.showAlert(`We've emailed you a link to reset your password. Please check your mail box and spam.`);

        console.log("4");
        delay(1500);
        this.navigationService.navigateTo('/login/auth');
        console.log('5')
    } catch (err) {
        this.utilitiesService.showAlert(err);
    } finally {
        this.loadingService.hideLoader();
    }
}

The test:

it('should submit email to reset password after submitting formulary', () => {
    component.form.setValue({
      email: '[email protected]',
    });

    const loadingService = TestBed.inject(LoaderService);
    const userService = TestBed.inject(UserService);
    const utilitiesService = TestBed.inject(UtilitiesService);
    const navigationService = TestBed.inject(NavigationService);

    fixture.detectChanges();

    const button = fixture.debugElement.nativeElement.querySelector('#button');

    spyOn(component, 'forgotPassword').and.callThrough();
    spyOn(loadingService, 'showLoader');
    spyOn(userService, 'apiUserSendPasswordResetLinkGet');
    spyOn(utilitiesService, 'showAlert');
    spyOn(navigationService, 'navigateTo');

    // Submitting form
    fixture.debugElement
      .query(By.css('form'))
      .triggerEventHandler('ngSubmit', null);

    expect(component.form.valid).toEqual(true);
    expect(button.disabled).toBeFalsy();
    expect(component.forgotPassword).toHaveBeenCalled();
    expect(loadingService.showLoader).toHaveBeenCalled();
    expect(userService.apiUserSendPasswordResetLinkGet).toHaveBeenCalled();
    expect(utilitiesService.showAlert).toHaveBeenCalled();
    expect(navigationService.navigateTo).toHaveBeenCalled();
  });

Every time I run and / or debug the test, I have the error

Expected spy navigateTo to have been called.

But the console never prints “3”, which means showAlert is also not being called and I should also have the same error regarding showAlert spy to be called, but I don’t.

I don’t know if this problem has to do if the await call to the API or something else. I would like to know how can I fix it, so all the test can pass as expected.

Thank you!

Login Form use ReactJS (without database) with map()?

I want to create a login form with array data:

const users = [
  {
    username: 'admin1',
    password: '12345678'
  },
  {
    username:'admin2',
    password:'012345678'
  }
];

and Login.js looks something like this:

import React from 'react';

class Login extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      userName: "",
      password: ""
    };
  }

  changeInputValue(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  validationForm() {
    let returnData = {
      error : false,
      msg: ''
    }
    const {password} = this.state
    //Check password
    if(password.length < 8) {
      returnData = {
        error: true,
        msg: 'Password must be more than 8 characters'
      }
    }
    return returnData;
  }

  submitForm(e) {
    e.preventDefault();
    const validation = this.validationForm()
    var username = e.target.elements.username.value;
    var password = e.target.elements.password.value;
    if (validation.error) {
      alert(validation.msg)
    }else if(username === 'admin1' && password === '12345678') {
      alert("Login successful");
    }else {
      alert("Wrong password or username");
    }
  }
    
  render() {
    return (
      <div className="container" style={{ paddingTop: "5%" }}>
        <form
          onSubmit={e => {
            this.submitForm(e);
          }}
        >
          <div className="form-group">
            <input
              type="text"
              className="form-control"
              name="username"
              placeholder="Username"
              onChange={e => this.changeInputValue(e)}
            />
          </div>
          <div className="form-group">
            <input
              type="password"
              className="form-control"
              name="password"
              placeholder="Password"
              onChange={e => this.changeInputValue(e)}
              
            />
          </div>
          <button value="submit" className="btn btn-primary" onClick={this.postDetails}>
            Submit
          </button>
        </form>
      </div>
    
    );
  }
}

export default Login;

So the above code only check whether the username and password fields entered in the form match the name and password of single record in the array of objects of User.js the above code is working fine. I don’t know how to check username and password from the passed array.

I want to use map () to check for username and password. Please show an instance of how it is done. Sorry, I’m new to ReactJS so I’m a bit confused, hope you can help. Thanks

Handling several promises in Javascript

Let’s say I have an array with a lot of promises. I don’t want to run them in sequence because that would be very slow but I don’t want all of them to run in parallel because that would overload the server. Each of this promises can be resolve or rejected very fast (around 1 second) or, in the worst case scenario, after something around 40 seconds. None of the promises depend on the result of any other. Which is the best way to handle this case? I have seen that an alternative is using Promise.all() in batches of 10 promises. However, the latter doesn’t seem to be efficient considering that I can have 9 promises resolving very fast, but 1 of them resolving very slow. What I would like the following:

Say I have 100 promises. I start processing 10 of them, as soon as one of them resolves, the 11th promise is processed, as soon as other one resolves, the 12th promise is processed, and so on. Notice this behavior is different from using Promise.all() in batches of 10 because in that case the 11th to 20th promise would be processed after all of the 1st to 10th promises are resolved.

Which is the best way of implementing this? I was picturing something like having a queue and having an async function processPromise that pops promises from that queue (until it is empty) and process them. I would then make an array of promises where each promise corresponds to an invocation of processPromise and then Promise.all() over that array. However, I’m not sure if concurrent access to that queue (that is share by different invocations of processPromise) would be an issue, or if I have nothing to worry about considering javascript is single-threaded.

Why isn’t my Number Guessing loop not working?

I’m totally new at Javascript. I just learned about the WHILE loop and I’m trying to create a simple number guessing game, but it doesn’t seem to be working. The program is supposed to work like this: The player has 3 tries to guess the random number from 1-5. If guessed wrong, an alert gives a hint whether or not the number is higher or lower. If guessed right, the program congratulates the player and exits the loop. The condition ” ( guessCounter < 3 || +guess !== randomNumber ) ” doesn’t seem to be working though. Perhaps it’s something else. Any help understanding why it’s not working is appreciated. Thanks.

// Generate random number
const randomNumber = Math.floor( Math.random() * 5 ) + 1;

//  Ask user for guess
let guess = prompt( "Guess a number between 1-5." );

//  Create guessCounter
let guessCounter = 1;

// Allow only 3 guesses. Each wrong guess will hint if the random number is higher or lower. If guessed correctly, congratulate player and exit loop. 


while ( guessCounter < 3 || +guess !== randomNumber ) {
    if ( +guess < randomNumber ) {
        alert(`You did not guess correctly. The number is higher.`);
        guessCounter+= 1;
        guess = prompt("Try again.");
    } else if ( +guess > randomNumber ) {
        alert(`You did not guess correctly. The number is lower.`);
        guessCounter+= 1;
        guess = prompt("Try again.");
    } else {
        alert(`You guessed the correct number. Congrats.`);
    }
};

How to allow CORS with Axios for public API using React

I am trying to build a react app that calls a public API using axios.get(url)to display match results from a game I play. I keep getting the error Access to XMLHttpRequest at 'url' from origin 'localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. which causes my GET request to fail.

I have tried looking at the Axios documentation and other stackoverflow posts on this issue but none of them seemed to have what I was looking for. Many of the answers were to allow CORS on the server-side but this is a public API so I don’t have access to the server. Is there a way to allow CORS just through the front-end react code using Axios to solve this problem? This react app is just for my own learning purposes and not for production so I do not need the best solution, I just want to be able to have my app work so that I can keep going on my project.

This is the code that I’m working with

        axios.headers = {"Access-Control-Allow-Origin": "true"};
        axios.get(url)
        .then(response => {
            //...code in here
        });

Should I use something else instead of Axios that would be easier?

Object property is showing as true but it’s false when I try to do anything with it [duplicate]

I’m trying do make a js chess board, and I only validate the pinned pieces moves, like so:

for (var j = 0; j < moves.length; j++) {
    console.log(this.position[1][moves[j].start])
    console.log(this.position[1][moves[j].start].isPinned)
    if (this.position[1][moves[j].start].isPinned || isInCheck) {
        this.makeMove(moves[j], false);
        // checks if king is in check
        this.unmakeMove(false)
    }
}

The first console.log logs the piece that’s trying to move, wich is an object, and if I manually see it’s “isPinned” key, it’s sometimes true, but even when it is true, the second console.log logs “false”.
I have no idea what is causing that, maybe some of you guys can help me

How to use more than one pubsub in javascript grapql?

I want to use Google PubSub and Redis PubSub provided by Google Cloud in Javascript GraphQL(apollo-server).

I tried to create 2 subscription fields, but I couldn’t get the result I wanted.

this, it said that subscriptions do not provide more than two root fields.

How can I subscribe to 2 pubSub objects?

The code I used is like below.

Subscription: {
    operation: {
      subscribe: withFilter(
        (_, { channelId }, { pubSub }) => pubSub.asyncIterator(getTopic(channelId)),
        (payload, variables) => {
        
            // Some Code...
           
        }
      ),
    },
  },