UseDropZone 400 bad request when uploading video like .mp4 or .mov

kind stuck at this problem for a long time. I tried different way for setting up accept area when use useDropzone based on MIME doc, but did not find the appropriate approach for uploading video, below are two approaches I tried.

It appears that I cannot upload video even without setting any accept condition and keep getting 400 bad request error {"error":{"message":"Invalid image file"}}

  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    accept: ['image/*', 'video/*', '.pdf'],
    maxSize: 300 * 1024, // 300KB
  });
  const { getRootProps, getInputProps } = useDropzone({
    onDrop,
    accept: {
      'image/*' : ['.png', '.jpg'],
      'video/*' : ['.mp4'],   //or 'video/mp4' : ['.mp4'] based on MIME
    },
    maxSize: 2 * 1024 * 1024 // 2MB
  });

also the second method is only working for first key ‘image/*’, if I change it to

 accept: {
   // 'image/*' : ['.png', '.jpg'],
      'video/*' : ['.mp4']
    }

it can only select mp4 when browse, but cannot upload with the same 400 bad request error.
Could someone help with this? Really thanks!!

the processing bar looks correct(color would become orange if error), but fail to upload

How can I get Webpack Dev Server to serve routes other than the root?

I am working on a project that requires me to pull from an couple APIs when I submit to a form. I have been able to successfully pull info in the prod build since it runs the server files I wrote, however I can’t seem to get Webpack Dev Server to run these files.

My file hierarchy:

__test__/
dist/
node_modules/
src/
- client/
- - css/
- - - css files
- - html/
- - - index.html
- - js/
- - - formhandler.js (relevant)
- - index.js
- server
- - app.js (sets up routes)
- - geonames.js (API request)
- - server.js (starts server on a port)
.babelrc
.eslintrc.json
.gitignore
package-lock.json
package.json
README.md
webpack.dev.js (relevent)
webpack.prod.js

webpack.dev.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    entry: './src/client/index.js',
    mode: 'development',
    devtool: 'source-map',
    stats: 'verbose',
    devServer: {
        port: 3030
    },
    module: {
        rules: [
            {
                test: /.js$/,
                exclude: path.resolve(__dirname, 'node_modules/'),
                loader: 'babel-loader'
            },
            {
                test: /.css$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            }
        ]   
    },
    plugins: [
        new HtmlWebpackPlugin(
            {
                template: "./src/client/html/index.html",
                filename: "./index.html"
            }
        ),
        new MiniCssExtractPlugin()
    ]
};

src/server/app.js

const express = require('express');
const APIResponse = require('./geonames.js');

const app = express();

app.use(express.static('dist'));

app.get('/api', async function (req, res) {
    const response = await APIResponse();
    res.json(response.body);
});


module.exports = app;

src/server/server.js

const app = require('./app');
const port = 3000;

app.listen(port, () => {
    console.log('Listening on localhost:3000');
});

module.exports = port;

src/client/js/formhandler.js

function handleSubmit(e) {
    let formText = document.getElementById('location').value;

    console.log(`handleSubmit ran with parameter: ${formText}`);

    e.preventDefault();

    fetch('http://localhost:3000/api'.toString())
    .then(res => res.json())
    .then(function(response) {
        console.log(response.body);
    });
}


export { handleSubmit };

ERRORS from dev build:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api. (Reason: CORS request did not succeed). Status code: (null).

Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.

Keep in mind everything works as expected when server is started via script running “node

React dynamic form bug

I’ve created script for dynamic form, but there’s 2 things which I can’t get and my head is exploding right now, hopefully somebody would help me with that.

  1. After creating new fields – I can’t remove fields depends on button which was clicked.
  2. And after removing some of those fields, I have this error with fieldsenter image description here
import React from "react";
import {useState , useEffect} from "react";
import ReactDOM  from "react-dom";
import "./index.css";


const Form = () =>{
  const [fieldsLength, fieldsLengthChanger] = useState(1);
  const [fields, fieldsChanger] = useState([{
    id : 1,
    name: "",
    phone: "",
    age: ""
  }])



  return  (
    <>
      <div className="form__wrapper">
        <h2>Form </h2>
        {
          fields.map((elem, index) => {
            return(
              <FormElement {...elem} fields={fields} fieldsChanger={fieldsChanger} fieldsLength={fieldsLength} fieldsLengthChanger={fieldsLengthChanger}/>
            )
          })
        }
        <AddMore fieldsLength={fieldsLength} fieldsLengthChanger={fieldsLengthChanger} fields={fields} fieldsChanger={fieldsChanger}/>
      </div>
    </>
  )
}


const FormElement = ({fieldsLength  ,...props}) =>{

  function inputHandler(e, id){
    console.log(e.target.name);
    const values = [...props.fields];
    values[id-1][e.target.name] = e.target.value;
    props.fieldsChanger(values);
  }

  function removeElement(e,id){
    e.preventDefault();
    var arr = [...props.fields];
    const newArray = arr.filter(function(elem,index){
      console.log("index:" , index, "ID : ", id);
      if (index + 1 != id){
        return elem;
      }
    });
    // console.log(newArray);
    // arr.splice(3, 1);
    props.fieldsChanger([])
    props.fieldsChanger(newArray);

    
  }

  return (
    <div className="group__form">
      <div className="form__element">
        <input type="text" value={props.fields.name} name="name" onChange={e => inputHandler(e , props.id)} />
      </div>
      <div className="form__element">
        <input type="text" value={props.fields.phone} name="phone" onChange={e => inputHandler(e , props.id)}/>
      </div>
      <div className="form__element">
        <input type="text" value={props.fields.age} name="age" onChange={e => inputHandler(e , props.id)}/>
      </div>
      {
        fieldsLength > 1 ? <div className="remove__field">
          <a href="#" onClick={e=>removeElement(e , props.id)}>Remove</a>
        </div> : ""
      }
    </div>
  )
}
const AddMore = (props) =>{
  function addMore(){
    props.fieldsLengthChanger(props.fields.length + 1);
    props.fieldsChanger([...props.fields, {id:props.fields.length + 1 , name: "" , phone : "" , age :''} ]);
    
  }
  return (
    <div className="add__more">
      <a href="#" onClick={e=> addMore()}>Add element</a>
    </div>
  )
}


ReactDOM.render(<Form/> , document.getElementById("root"));

Where I’m wrong – would be really helpfull to understand what is the problem

How can I capture an audio stream from another tab and make it into a valid input for Web Audio API for visualization?

I am building an app that I want to be able to capture browser audio from say Spotify or YT. And then make it so that I can turn it into a live stream to input into Web Audio API to create visuals while the audio plays. I’ve came across technologies like Jack and MediaCapture API but wanted to know if anyone has an efficient approach. Any ideas and suggestions are appreciated greatly.

Problem printing Linked List Item in Javascript

I want to print all of my linked List item using Javascript. Here I create Node class for this. But My printlist() method prints undifined. Can any one help me?

Here Is my Code:

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
    this.head = null;
  }
  setNextNode(node) {
    this.next = node;
  }

  getNextNode() {
    return this.next;
  }

  printlist() {
    let newhead = this.head;
    let output = " ";
    while (newhead !== null) {
      output += newhead.data + ' ';
      console.log(output);
      newhead = newhead.getNextNode(this.next);
    }
  }
}

const n1 = new Node(1);
const n2 = new Node(2);
const n3 = new Node(3);
n1.next = n2;
n2.next = n3;
//console.log(n1);
console.log(n1.printlist());

Is web worker unavailable when cross-origin isolation is enabled

Here are my two files, test.js and test.php.

test.js:

console.log("test.js is loaded")

test.php:

<?php
header('Content-Type: text/html; charset=UTF-8');
//header('Cross-Origin-Embedder-Policy: require-corp');
//header('Cross-Origin-Opener-Policy: same-origin');
?><!DOCTYPE html>
<html>
<title>test</title>
<script>
new Worker("/test.js")
</script></html>

The browser console prints “test.js is loaded” as expected.
But if I comment out the two lines in test.html, nothing would be printed in the browser console, which means there’s a problem that prevents the worker from being loaded if I enable the cross-origin isolation policy.
So is there a correct way to use worker with the cross-origin isolation policy enabled?

BTW, I have to enable the cross-origin isolation policy because I need to use SharedArrayBuffer.

I am unable to pass my button’s event into my function’s parameter

   <script>

  const scorePlayer = document.getElementsByClassName("playerScore")
  const scoreComputer = document.getElementsByClassName("computerScore")
  const selections = document.querySelectorAll("button")
  const results = document.getElementsByClassName("Results")


  selections.forEach(selection =>{selection.addEventListener('click', function (){
    playRound(selection.value)
  })
})

  let playerScore = 0
  let computerScore = 0

  function computerPlay() {
    const selections = [rock, paper, scissors]
    return selections[Math.floor(Math.random()*selections.length)];
  }

  function playRound(playerSelection) {

    let computerSelection = computerPlay()
    let result = ""

    if (playerSelection == "rock" && computerSelection == "scissors" || playerSelection == "paper" && computerSelection == "rock" || playerSelection == "scissors" && computerSelection == "paper") {
       result = ("you win! " + playerSelection + " beats " + computerSelection + "!") 
       playerScore += 1      
    }
    if (playerSelection == "scissors" && computerSelection == "rock" || playerSelection == "rock" && computerSelection == "paper" || playerSelection == "paper" && computerSelection == "scissors") {
       result = ("you lose! " + computerSelection + " beats " + playerSelection + "!") 
       computerScore += 1
    }
    else if (playerSelection == computerSelection) {
       result = ("its a draw");
    }
    results.innerhtml = result 
   return
   }

   scorePlayer.innerhtml = playerScore
   scoreComputer.innerhtml = computerScore
   
  

</script>

i am trying to make a simple rock paper scissors game and so far i’ve written this much code but im not sure how to get the value of my buttons (rock, paper, scissors) to pass through my function parameters.
i have identified the values in javascript using an array but also in html using “value =” inside the button tag of the selection

setTime() replacement in php

I want to convert below javascript code to PHP

<script>    
     noon = new Date();
     alert(noon);
     noon.setTime(1641951202187.3433);
     alert(noon);   
</script>

returning value Wed Jan 12 2022 07:03:22 GMT+0530 (India Standard Time)

As in javascript setTime() function Add 1641951202187.3433 milliseconds to January 1, 1970.
But i am unable to find such function in php or solution

Handle Date Gaps in Chart JS

I am plotting a graph using chart js. I have a couple of inconsistent data. For instance, the example data I have shared starts with 1909 and the next is 1960. In other cases, they are properly displayed: 1980, 1981, 1982…

Is there a way for me to handle specific data with gaps? For instance, have the year displayed sequentially.

const ctx = canvas.getContext("2d");
const myChart = new Chart(ctx, {
    type: "line",
    data: {
        labels: labels,
        datasets: [{
            label: "Country Population",
            data: data,
        }, ],
    },
    options: {
        scales: {
            x: {
                title: {
                    display: true,
                    text: "Year",
                },
                xAxes: [{
                    type: 'time',
                    time: {
                        unit: 'year'
                    }
                }]
            },

            y: {
                title: {
                    display: true,
                    text: "Population",
                },
            },
        },
    },
});

enter image description here

an array of map objects in qml (javascript)

I’m trying to save object maps using javascript array in qml

property var arrayData: []
onClicked: {                          
  arrayData.push(mapData)
}

and when I print the array:

for(var i = 0; i < arrayData.length; i++) {
  print("t ******** " + i + " ********")
  for(const [key, value] of arrayData[i].entries()) {                        
    print(key + " : " + value)
  }
  print("t ******** " + i + " ********")
}

terminal:

  qml:     ******** 1 ********q
  qml: D:/V 0.0.53.34/data.csv : PaSide_dBm,Toa Main
  qml:     ******** 0 ********
  qml:     ******** 1 ********
  qml: D:/V 0.0.53.34/data.csv : PaSide_dBm,ToaMain
  qml:     ******** 1 ********

when i add a new map to the array the other maps will change too
meaning the first element and second element are not the same
i don’t know why ):
so how can i create an array of maps?

thanks in advance

Fullcalendar custom event modal appearing under custom events

I’m using FullCalendar in a React/Typescript project. I’m using eventContent to create a custom event and added a modal that appears when you click on the event.
For some reason the modal frequently appears below some of the events. I’ve tried adding a position and z-index to the modal as well as the event but it doesn’t help. When looking at the FullCalendar css, the z-indexes of the events and grids are 1 or 2. I’ve added a background color and z-index of 999 in one of the screenshots to show that the events still pop through for some reason.

Here are some screenshots of the issue:

Events overlapping modal – 1

Events overlapping modal – 2

Modal wrapper with a background of red and z-index of 999

Here’s the code:

Full Calendar Component:

<FullCalendar
        // buttonText={{
        //   today: "Today",
        //   month: "Month",
        //   week: "Week",
        //   day: "Day",
        //   list: "Agenda",
        // }}
        // contentHeight="auto"
        ref={calendarRef}
        allDaySlot
        dateClick={(obj) => console.log(obj)}
        dayCellContent={(obj) => (
          <DayCell currentView={currentView} obj={obj} />
        )}
        dayHeaderContent={(dateObj) => (
          <DayHeader
            currentView={currentView}
            date={dateObj.date}
            dateObj={dateObj}
          />
        )}
        // eventSources={[
        //   { url: "/src/data/[email protected]", format: "ics" },
        // ]}
        dayMaxEventRows={3}
        // initialEvents={}
        drop={(obj) => {
          console.log(obj.draggedEl);
        }}
        droppable
        editable
        eventClick={(obj) => {
          // console.log(obj);
        }}
        eventContent={(obj) => <CalendarEvent obj={obj} />} *** LOOK HERE***
        eventDrop={(obj) => handleResizeAndDrop(obj)}
        eventResizableFromStart
        eventResize={(obj) => handleResizeAndDrop(obj)}
        events={events}
        eventSources={[eventSources()]}
        firstDay={0}
        headerToolbar={false}
        height="100%"
        // expandRows
        initialView={currentView}
        nowIndicator
        nowIndicatorContent={(NowIndicatorContentArg) => (
          <div ref={nowLineRef} className={styles.customArrow}>
            {/* <div
              style={{
                height: "100%",
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <IoCaretForward />
            </div> */}
            <div className={styles.arrowText}>
              {moment(NowIndicatorContentArg.date).format("h:mm A")}
            </div>
          </div>
        )}
        plugins={[
          dayGridPlugin,
          timeGridPlugin,
          listPlugin,
          interactionPlugin,
          iCalendarPlugin,
        ]}
        scrollTime={moment(Date.now()).format("hh:mm:ss")}
        select={(obj) => handleSelectDate(obj)}
        selectable
        slotDuration="1:00"
        // eventContent={(obj) => (
        //   <div style={{ background: "red" }}>{obj.backgroundColor}</div>
        // )}
        slotLabelContent={(obj) => (
          <SlotLabel nowLineOffset={nowLineRef} time={obj.date} />
        )}
        snapDuration="00:15:00"
      />

Custom Calendar Event Css:

//Event
.eventContent {
  position: relative;
  height: 100%;
  z-index: 1 !important;
}

//Event details
.detailContainer {
  position: relative;

  width: 448px;
  color: black;
  padding: 5px;
  z-index: 1000 !important;
}

Any help or insight would be greatly appreciated.

Respuesta de Django se pierde y no llega la promesa al fetch

Tengo un formulario el cual recibe js para realizar una serie de validaciones y enseguida por fetch envió la información al servidor (una api sencilla). La verdad no tengo muy entendido en sí por qué se da el error, cabe recalcar que en desarrollo funcionaba perfecto pero ahora que está en producción alojado en heroku se produce dicho problema, el código fetch es el siguiente.

formulario.addEventListener('submit', (e) => {
    e.preventDefault();

    fetch('https://portafolioadrian.herokuapp.com/contacto', {
      method: 'POST',
      body: JSON.stringify({
        nombre: document.querySelector('#nombre').value,
        correo: document.querySelector('#correo').value,
        telefono: document.querySelector('#telefono').value,
        mensaje: document.querySelector('#form__message').value,
        terminos : document.getElementById('terminos').checked,
      }),
      headers: {
        'X-CSRFToken': getCookie('csrftoken'), "Accept": "application/json", 'Content-Type': 'application/json'} 
    })
    .then(res => res.json())
    .then(res => {
      if (res.success) {
        formulario.reset();
    
            document.getElementById('form__message-success').classList.add('form__message-success-active');
            setTimeout(() => {
                document.getElementById('form__message-success').classList.remove('form__message-success-active');
            }, 5000);
    
            document.querySelectorAll('.form__group-correct').forEach((icono) => {
                icono.classList.remove('form__group-correct');
            });
      }else{
        document.getElementById('form__message').classList.add('form__message-active');
      }
    })  
});

Al momento de enviarlo, por consola me sale el siguiente error

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at
position 0

Y en la sección de network el estatus al momento de realizar el POST es 301 Moved Permanently, he investigado algo y trata hacerca de redirecciones pero no encontré solución.

El urls.py de la app es esta:

urlpatterns = [
    path('', views.contacto, name='contacto'),
    path('mensajes/', views.mensajes, name='mensajes'),
]

Y la view es la siguiente:

def contacto(request):

    if request.method == "POST":
        
        #Obtengo los datos y los convierto en diccionario y asigno datos a variables
        data = json.loads(request.body)
        nombre = data['nombre']
        correo = data['correo']
        telefono = data['telefono']
        mensaje = data['mensaje']
        terminos = data['terminos']

        #Creo y guardo el registro en la base de datos 
        instancia = Contacto.objects.create(nombre = nombre, email = correo, telefono = telefono, mensaje = mensaje, terminos = terminos)
        instancia.save()

        #Devuelvo la respuesta al fetch para terminar de renderizar datos en la plantilla de contacto
        return JsonResponse('success')

    else:
        #renderizo el formulario html
        return render(request, 'contacto/contacto.html')