Communication with backend through parse doesnt work in build but in dev mode with Quasar and vite

Im using quasar together with Vite and parse with back4app. I am having problems communicating with the parseserver after I build the app. It works fine in developmentmode.

How can I make this to work also with Vite? I havnt really changed any settings in quasar.config.js

In development mode I get the output as expected but once it is build I get:

IndexPage.23035fcf.js:1 Error fetching data: TypeError: J.default.fromJSON is not a function
    at index.395acdc3.js:4:16160
    at Array.map (<anonymous>)
    at index.395acdc3.js:4:16037
    at async o (IndexPage.23035fcf.js:1:1247)
o @ IndexPage.23035fcf.js:1
await in o (async)
h.onClick.e.<computed>.e.<computed> @ IndexPage.23035fcf.js:1
ot @ index.811214c9.js:1
Re @ index.811214c9.js:1
ml @ index.811214c9.js:1
B @ QBtn.bc39fdca.js:1
S @ QBtn.bc39fdca.js:1
ot @ index.811214c9.js:1
Re @ index.811214c9.js:1
n @ index.811214c9.js:1
IndexPage.23035fcf.js:1 Error fetching data: Error: Failed to fetch data from Parse.
    at o (IndexPage.23035fcf.js:1:1317)

My boot file in boot folder in quasar:

import Parse from "parse";

export default async ({ app }) => {
  const appId = import.meta.env.VITE_PARSE_APPLICATION_ID;
  const jsKey = import.meta.env.VITE_PARSE_JS_KEY;
  const parseKey = import.meta.env.VITE_PARSE_CLIENT_KEY;

  Parse.initialize(appId, jsKey, parseKey);

  Parse.serverURL = "https://parseapi.back4app.com"; // Set your Parse server URL

  // Attach Parse to Vue instance or global scope if needed
  app.config.globalProperties.$parse = Parse;
};

This is my component for query:
const query = new Parse.Query(“UploadedFiles”);
let results = “”;

try {
  results = await query.find();
} catch (error) {
  console.error("Error fetching data:", error);
  throw new Error("Failed to fetch data from Parse.");
}

console.log("Response:", results); // Log response status

This is my .env:

VITE_PARSE_URL=https://parseapi.back4app.com
VITE_PARSE_APPLICATION_ID=XXXXXXXXXXXXXXXXXXXXXXXXXX
VITE_PARSE_JS_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXX
VITE_PARSE_CLIENT_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXX
VITE_PARSE_KEY=PARSE_CLIENT_KEY

Why am I getting false in the console when I should be getting true? [closed]

Why do I get false in the console? It should be true.

I have tried changing the word and values, but I get nothing other than false in the console

const a = 1;
const b = 3;
const x = "a";
const pwd = "abekat";

function theCrown(a, b, x, pwd) {
  let arr = pwd.split("");
  let counter = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === x) {
      counter += 1;
    }

  }
  return counter >= a && counter <= b;
}

console.log(theCrown(a, b, x, pwd));

Woocommerce Admin Order Edit Custom Meta Toggle

I’m using this snippet to add a custom checkbox to the order edit page that I will use to override some automations that I’ve implemented.

// Add a custom meta box to the order edit page
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box',
        'Custom Meta Box',
        'render_custom_meta_box',
        'shop_order',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'add_custom_meta_box');

// Render the custom meta box content
function render_custom_meta_box($post) {
    // Retrieve the current value of the custom meta field
    $custom_field_value = get_post_meta($post->ID, '_custom_field', true);

    // Output the checkbox
    ?>
    <label for="custom_checkbox">
        <input type="checkbox" id="custom_checkbox" name="custom_checkbox" <?php checked($custom_field_value, 1); ?> />
        Toggle Custom Field
    </label>
    <input type="hidden" name="_custom_field" id="_custom_field" value="<?php echo esc_attr($custom_field_value); ?>">
    <?php
    // Enqueue the JavaScript script
    wp_add_inline_script('jquery', '
        jQuery(document).ready(function($) {
            // Toggle the value of the custom meta field when the checkbox is clicked
            $("#custom_checkbox").change(function() {
                var checkboxValue = $(this).prop("checked") ? 1 : 0;
                $("#_custom_field").val(checkboxValue);
            });

            // Update the hidden input when the checkbox state changes
            $("#_custom_field").val($("#custom_checkbox").prop("checked") ? 1 : 0);
        });
    ');
}

// Save the custom meta field value when the order is saved
function save_custom_meta_box($post_id) {
    if (isset($_POST['custom_checkbox'])) {
        update_post_meta($post_id, '_custom_field', 1);
    } else {
        update_post_meta($post_id, '_custom_field', 0);
    }
}
add_action('save_post', 'save_custom_meta_box');

It works as intended. The only issue is that I have to update the order twice to get it to take effect. I’m guessing it has something to do with how and when the order is saved, but I can’t figure it out.

How does CreepJS detect headless Chrome by web worker user agent?

I’m studying some scraping techniques. So far, I use headless Chrome 119, [email protected] and [email protected]. I try to bypass CreepJS checks: https://abrahamjuliot.github.io/creepjs/

There is one check I can’t understand, it is Worker/userAgent:

CreepJS Worker section screenshot

My navigator.userAgent is successfully overridden by

const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36';
await page.setUserAgent(userAgent);

But Worker.userAgent is still headless. To understand this behavior and how to avoid it, I tried to implement my own web worker like

<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <h3>Worker test</h3>
        <script>
            function sleep(ms = 0) {
                return new Promise(r => setTimeout(r, ms));
            }

            async function checkWorkerNavigator() {
                const w = new Worker('worker_test.js');

                let ready = false, res = undefined;

                // console.log(window.navigator.userAgent);

                w.onmessage = (e) => {
                    ready = true;
                    res = e.data;
                    console.log(res);
                };
            }

            window.onload = function() {
                checkWorkerNavigator();
            }
        </script>
    </body>
</html>
// worker_test.js
postMessage(self.navigator.userAgent);

but this dummy page returns overridden “headful” UA (Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36) when I access it by my headless Chrome.

The web worker code of CreepJS seems way more complex than mine, https://github.com/abrahamjuliot/creepjs/blob/master/src/worker/index.ts , and I failed to figure out how to create web worker to make it return actual headless user agent.

Any guide or article about the reason of difference between navigator’s and web worker’s user agents would be appreciated.

How to display items in order 1,2,3 in React? [closed]

How do I display each item in an order of 1,2,3,4,5 and keep going according to several items similar to <ol> and <li>
tags in HTML? How can I do that same thing
in React? I tried one solution to add a text of each index + 1 but then it breaks the UI and the list goes here and
there so any better way to do that?

By each item in an order i mean something like this https://www.w3schools.com/html/html_lists.asp#:~:text=An%20ordered%20HTML%20list%3A

        <div className='ml-auto mt-8 md:m-12'>
            <h1 className='break-words text-2xl text-white font-bold'>Items</h1>
            <div className='flex flex-wrap m-5 gap-4'>
                {data.map((item) => (
                <ol className='flex items-center m-2'>
                    <li className='text-white'>{item.name}</li>
                </ol>
                ))}
            </div>
        </div>

I also tried to do something like this

 <div className='ml-auto mt-8 md:m-12'>
        <h1 className='break-words text-2xl text-white font-bold'>Items</h1>
        <ol className='flex flex-wrap m-5 gap-4'>
          {data.map((item, index) => (
            <li key={index} className='flex items-center m-2 text-white'>
              {item.name}
            </li>
          ))}
        </ol>
      </div>

It should work like this:

<!DOCTYPE html>
<html>
<body>
<h2>An Ordered HTML List</h2>
<ol>
  <li>Dog</li>
  <li>Tea</li>
  <li>Milk</li>
</ol> 

</body>
</html>

extending js (maplibregl) library with new namesapce

I want to create a new js library on top of maplibregljs.

My newLibrary.js

import maplibreGl from './lib/maplibre-gl.js'

class MyNewMap extends maplibreGl{

  //my custom constructor and features
}

My index.js

var myMap= new MyNewMap.Map({
//...
});

If I write the contents of both files together in one file then everything works as expected. But if I import them in the above sequence, i.e. newLibrary.js and index.js in my webpage, then I get an error Uncaught ReferenceError: MyNewMap is not defined at HTMLDocument.<anonymous> (index.html)

I tried bundling the newLibrary.js using esbuild --bundle --minify with formats iife,esm etc as well. Not sure how to handle it as I am not very familiar with js namespaces. Please help by giving clean ways to extend the Js library in order to build a new library on top of it.

Nextjs not sending csrf token to my django server

My code is working on localhost and I can see csrf by console log

enter image description here

but when deploy on my server https I don’t see csrf token and it’s null I don’t know why

enter image description here

I am struggling to solve this problems from past few days and still now don’t have any solution. I am not understanding why it’s not working on production when deploy on my server but same code working on localhost. here is my react code for axois post

 const handleClickComment =  (main_comment_id)=>{
   
  const csrfToken =  cookies.get("csrftoken")
   axios.post(url,comment_data,{
      withCredentials:true,
      headers: {
        'X-CSRFToken': csrfToken, // Adding the CSRF token to the request headers
      }, 

my django settings.py

AUTHENTICATION_BACKENDS = [
    
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by email
    'allauth.account.auth_backends.AuthenticationBackend',
     
]


CORS_ALLOWED_ORIGINS = [
    "http://*",
    "https://*",
    "http://localhost:3000",
    "https://localhost:3000",
    "http://127.0.0.1:3000",
    "https://127.0.0.1:3000",
]

CORS_ORIGIN_WHITELIST = [
    'http://*',
    "https://*", 
    "http://localhost:3000",
    "https://localhost:3000",
    "http://127.0.0.1:3000",
    "https://127.0.0.1:3000",
]


CSRF_TRUSTED_ORIGINS = [
    
         'http://*',
         "https://*",
         "http://localhost:3000",
         "https://localhost:3000",
         "http://127.0.0.1:3000",
         "https://127.0.0.1:3000",
         
                                            
                         
                        ]
 
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True




CORS_ALLOW_HEADERS = default_headers + (
    'xsrfheadername',
    'xsrfcookiename',
    'content-type',
    'x-csrftoken',
)


CSRF_COOKIE_SAMESITE = 'Strict'
SESSION_COOKIE_SAMESITE = 'Strict'
CSRF_COOKIE_HTTPONLY = False  # False since we will grab it via universal-cookies
SESSION_COOKIE_HTTPONLY = True

I am using django rest API. here is my api function which I warped with @csrf_exempt

@csrf_exempt
@api_view(["GET","POST","PUT","DELETE"])
def CommentAPI(request, slug):

Django view returning ‘Invalid request method’ despite valid AJAX POST request

I’m working on a Django project where I’m using JavaScript to make an AJAX POST request to a Django view named submit_post. Despite ensuring that the request headers, method, and data are correctly set, the view consistently returns a response of “Invalid request method.” I’ve verified that the X-Requested-With header is set to XMLHttpRequest, the request method is set to “POST”, and the data is correctly formatted as JSON. I’ve verified this in the network tab looking at the request headers and the payload.

I’ve ensured that the Django view function (submit_post) is designed to handle POST requests with the correct headers, specifically checking for XMLHttpRequest.

I’ve verified that the JavaScript AJAX request is sending a POST request with the correct headers, including X-CSRFToken and Content-Type: application/json; charset=utf-8 and checked the payload data to ensure it’s formatted as JSON.

I’ve also reviewed the middleware settings in Django, ensuring that necessary middleware, such as CommonMiddleware and CsrfViewMiddleware, is included. Restarted the server, cleared the cache, running it incognito mode and also making sure its not caused by any CORS-issues.

This is the JavaScript code:


$(document).ready(function () {

    // Capturing our form submission
    $("#submitPost").click(function (event){

        // Preventing the default form submission
        event.preventDefault();

        // Getting the CSRF token 
        var csrfToken = $("input[name=csrfmiddlewaretoken]").val();

        // Colleting our data
        var postContent = $("#postContent").val();

        // Formatting the data as JSON data
        var jsonData = JSON.stringify({"postContent": postContent});

        // Sending the AJAX request
        $.ajax({
            type: "POST",
            url: "/submit_post", 
            contentType: "application/json; charset=utf-8",
            headers: {"X-CSRFToken": csrfToken, "X-Requested-With": "XMLHttpRequest"},
            data: jsonData,
            success: function (response) {
                console.log('Success:', response);
            },
            error: function (error) {
                console.error(error);
            },
        });
    });
}); 

And this is the Python code:

def submit_post(request):
    if request.method == "POST":
        if request.headers.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
            try:
                # Retrieving data from the request body for JSON data
                data = json.loads(request.body.decode('utf-8'))
                post_content = data.get("postContent")

                # Log the received data
                print(f"Received Data: {data}")

                # Save post_content to the database
                new_post = Post(author=request.user, content=post_content)
                new_post.save()

                response_data = {'message': 'Post submitted successfully'}
                return JsonResponse(response_data)

            except json.JSONDecodeError as e:
                # Handle JSON decoding errors
                return JsonResponse({'error': 'Invalid JSON data'}, status=400)

    return HttpResponse("invalid request method")

So this last line in the Python code is what’s being triggered!

How do i save state of toggle checkbox on or off in user interface

Newbie to front-end world…I have a use case specifically in which i need to save toggle state on or off depending on user choice.

  1. If a user has previously selected toggle ON then i need to make sure that toggle is on for that particular user next time he or she visits the page.
  2. if a user has previously selected toggle OFF then i need ot make sure that toggle is off for that particular user next time her or she visits the page.

Below is my html implementation

<div class="toggle-checkbox">
    <label class="showLabel" for="show">Toggle on or off :</label>
    <label class="toggle">
      <input class="toggle-input" id="togBtn" type="checkbox" (click)="validate()" />
      <span class="toggle-label" data-off="OFF" data-on="ON"></span>
      <span class="toggle-handle"></span>
    </label>
  </div>
</div>

In the external typescript file i am trying to save the state like this –

validate(){
    var input = document.getElementById('togBtn') as HTMLInputElement;
    
    if (input.checked) {
          localStorage.setItem('togBtn', 'true');
      
        } else {
          localStorage.setItem('togBtn', 'false');
        }

}

tried this in typescript file but everytime i tried to re-visit the page with same request information then the toggle information is not saved for that user. I would appreciate any help.

Carousel Image Update Issue in React

I’m currently working on a React project that involves creating a carousel slider, and I’ve run into a few issues. First, when I am attempting to display the initial set of three images with the slice method, the arrow buttons to navigate between images are not working as expected. It seems like the currentIndex is not updating correctly.

Expected Behavior: Clicking the arrow buttons should smoothly transition to the next or previous image one by one. Thanks in advance for your attention 🙂
enter image description here

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";

import { Arrows, ImageContainer, ProvaSocialContainer, TextContainer } from "../styles/ProvaSocial.style";

import imagem1 from "../assets/antes-e-depois/olhos.png";
import imagem2 from "../assets/antes-e-depois/2.png";
import imagem3 from "../assets/antes-e-depois/3.png";
import imagem4 from "../assets/antes-e-depois/4.png";
import imagem5 from "../assets/antes-e-depois/5.png";
import imagem6 from "../assets/antes-e-depois/6.png";
import imagem7 from "../assets/antes-e-depois/7.png";
import imagem8 from "../assets/antes-e-depois/8.png";


const images = [imagem1, imagem2, imagem3, imagem4, imagem5, imagem6, imagem7, imagem8];

export const ProvaSocial = () => {
  const [currentIndex, setCurrentIndex] = useState(0);

  // this updates the currentIndex to the next index in order to change the image and if it reaches the end of the array it cycles back.
  const handleNext = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex + 1 === images.length ? 0 : prevIndex + 1
    );
  };
// this does the same as the handleNext function, but this time in reverse order. This allows us to go back to images.
  const handlePrevious = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex - 1 < 0 ? images.length - 1 : prevIndex - 1
    );
  };

  const handleDotClick = (index) => {
    setCurrentIndex(index);
  };

  return (
    <ProvaSocialContainer>
      <TextContainer>
        <h3>Sem corte e sem cirurgia</h3>
        <p>Confira alguns resultados da clínica Anastásia Estética Avançada</p>
      </TextContainer>
      <ImageContainer>
          <Arrows onClick={handlePrevious}>
          <svg
            xmlns="http://www.w3.org/2000/svg"
            height="20"
            viewBox="0 96 960 960"
            width="20"
          >
            <path d="M400 976 0 576l400-400 56 57-343 343 343 343-56 57Z" />
          </svg>          
        </Arrows>
      {/* to get the first three images from the images array and renders them as initial images. */}
      {images.slice(0, 3).map((image, index) => (
          <img
            key={index}
            src={image}
            alt={`Slide ${index + 1}`}
            className={currentIndex === index ? "active" : ""}
          />
        ))}
        <Arrows onClick={handleNext}>
          <svg
            xmlns="http://www.w3.org/2000/svg"
            height="20"
            viewBox="0 96 960 960"
            width="20"
          >
            <path d="m304 974-56-57 343-343-343-343 56-57 400 400-400 400Z" />
          </svg>
          </Arrows>
        
        <div className="indicator">
          {images.map((_, index) => (
            <div
              key={index}
              className={`dot ${currentIndex === index ? "active" : ""}`}
              onClick={() => handleDotClick(index)}
            ></div>
          ))}
        </div>
      </ImageContainer>
    </ProvaSocialContainer>
  );
};

Memory leaks using node.js

I’m having trouble finding what causes memory leaks in my nodejs application.
I built an application that redirect the music of a youtube video to the speakers.
It seems like every time I add a song the memory never decreases but only increases even if it shouldn’t.

This is a portion of the code:

class MusicPlayer{
    
    constructor(onEvent){
        
        this.stream = null;

    }

    playNext(url){

        let video = ytdl(url, {

            quality: 'highestaudio',
            highWaterMark: 1 << 25,
            filter: format => format.container === 'webm' && format.audioQuality === "AUDIO_QUALITY_MEDIUM"

        });

        let audio = ffmpeg()
            .input(video)
            .addOption('-f s32le')
            .addOption('-acodec pcm_s32le')
            .addOption('-ac 2')
            .addOption('-ar 88200')
            .on('error', (err) => {
                console.log(err.message);
            }).on('start', () => {
                this.onEvent('start', songID);
            });


        this.stream = audio.pipe(new speaker({
            channels: 2,          // 2 channels
            bitDepth: 32,         // 32-bit samples
            sampleRate: 88200,
            highWaterMark: 1 << 25
        }));

        this.stream.on('finish', () => {
            this.stream.destroy();
            video.destroy();
            audio.emit('end');
            this.stream = null;

        });

    
    }

    play(url){
        
        this.stopCurrentSong();
        this.playNext(url);

    }

    stopCurrentSong(){

        if(this.stream !== null && this.stream !== undefined){

            this.stream.emit('finish');

        }

    }

Every time i want to play a new song the function play(url) is called.

Use axios interceptor to refresh the token for Next-Auth?

I setup Next-Auth and Axios for my NextJs project. I used method getSession() from Next-Auth for axios header. Like this

export const ApiAuth = () => {
  const instance = axios.create({
    baseURL: API_URL,
  });

  instance.interceptors.request.use(async (request) => {
    const session = await getSession();
    console.log(session);

    if (session) {
      request.headers["Authorization"] = `Bearer ${session.tokens.accessToken}`;
    }
    return request;
  });

  instance.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      console.log(`error`, error);
      if (error.response.status === 401) {
        console.log("Let refresh Here");
        console.log("And update Next-Auth session data");
      }
    }
  );

  return instance;
};

But I don’t know how can I update Next-Auth session data from axios interceptor. Could you please show me the way.

I imagine that I will create an api like /api/auth/refresh and this api handle update new access token and refresh token for Next-Auth and return new access token for axios.

amazon-ivs-web-broadcast voice of host is getting recorded but voice of attendees person is not recorded

I am using amazon-ivs-web-broadcast.js(https://web-broadcast.live-video.net/1.6.0/amazon-ivs-web-broadcast.js) to record meetings, when i see the live stream, voice of host is coming but voice of another person who is attending the meeting is not coming on live stream
Can some one help do we need extra configuration for capturing attendees voice in IVS

Here is my code

async createBroadcast(resolution: string,channelType: string) {
        if(typeof window != "undefined" && window.IVSBroadcastClient){
            try {
                const streamConfig = this.getConfigFromResolution(resolution,channelType);
                this.broadcastClient = window.IVSBroadcastClient?.create({
                    streamConfig: streamConfig
                  })
                
                return this.broadcastClient;
              } catch (error) {
                this.errorMsg = IVSErrorMsg.error_creating_stream
              }
        }
    } 
    async createVideoStream(name: string,deviceId: string) {

      try {
        if(this.broadcastClient && this.broadcastClient.getVideoInputDevice(name)){
          const videoStreamOld = this.broadcastClient.getVideoInputDevice(name);
          for (const track of videoStreamOld.source.getVideoTracks()) {
            track.stop();
          }
          await this.broadcastClient.removeVideoInputDevice(name);
        }
        const videoStream = await navigator.mediaDevices.getUserMedia({
          video: {
            deviceId: { exact: deviceId },
            width: {
             ideal: widthVideo.ideal,
             max: widthVideo.max,
           },
           height: {
             ideal: heightVideo.ideal,
             max: heightVideo.max,
           },
          aspectRatio: aspectVideo.ideal,
          frameRate: frameRateVideo,
          },
          audio: true,
        });
        if (this.broadcastClient) await this.broadcastClient.addVideoInputDevice(videoStream, name, { index: 0 });
  
      } catch (error) {
        this.errorMsg = IVSErrorMsg.error_adding_video
      }
     };
  
    async createAudioStream(name: string,deviceId: string) {
     
         try {   
         
        if (this.broadcastClient && this.broadcastClient.getAudioInputDevice(name)) {
     
         const audioStreamOld = this.broadcastClient.getAudioInputDevice(name);
         for (const track of audioStreamOld.source.getAudioTracks()) {
          track.stop();
         }
     
         await this.broadcastClient.removeAudioInputDevice(name);
       }
       
         const audioStream = await navigator.mediaDevices.getUserMedia({
         audio: {
           deviceId
         },
       });
       if (this.broadcastClient) await this.broadcastClient.addAudioInputDevice(audioStream,name);
         } catch (error) {
           console.log("error",error)
         }
         
    };
 const init = async () => {
      try {
        broadcastClient?.createBroadcast(resolution,channelType);
       
        await createVideoStream(CAM_LAYER_NAME,devices.webcam.id);
        await createAudioStream(MIC_LAYER_NAME,devices.speaker.id);
        await startBroadcast(stream_key,ingest_server)
      } catch (error) {
        console.log("error",error)
      }

    
    };