How do I get my json response to appear in my frontend console log

I’m trying to get my json response onto my frontend but I can’t get my front end to console log the response. My backend response looks like this:

[{"data":[
    {
      gid: 'XXXXXXXXXXX',
      name: 'XXXXXXXXXXX',
      resource_type: 'task',
      resource_subtype: 'default_task'
    },
    {
      gid: 'XXXXXXXXXXX',
      name: 'XXXXXXXXXXX',
      resource_type: 'task',
      resource_subtype: 'default_task'
    }
],"next_page":null}

My frontend code:

  const [tickets, setTickets] = useState(null)

  useEffect(() => {
  axios.get('http://localhost:5000/get-tasks').then(response => {
    const dataObject = response.data.data;
    
    const arrayOfKeys = Object.keys(dataObject || {});
    const arrayOfData = Object.keys(dataObject || {}).map((key) => dataObject[key]);

    console.log(arrayOfKeys);
    console.log(arrayOfData);
  });
}, []);

Replace certain part of a canvas with image

I am trying to replace a part of an HTML canvas with an image. The concept is to put a background image on the canvas that has solid colors. Let’s say red and now I make the code loop over the pixels of the image and if the pixels are matched with red then it replaces it with a certain image. Everything works fine but certain images looked zoomed in, I think there’s an issue with the drawImage function that I am using.

The code:

// Create a canvas element
        var canvas = document.createElement("canvas");
        canvas.setAttribute("id", `canvas${canvasn}`);
        
        // document.body
        var main_room = document.getElementById('canvas_frame');
        main_room.appendChild(canvas);
        var ctx = canvas.getContext("2d");

        // Load the original image
        var img = new Image();
        img.src = my_image;

        // on load

        document.getElementById('loader').classList.add("myloader");

        img.onload = function () {
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);

          // Get the image data
          var imgData = ctx.getImageData(0, 0, img.width, img.height);
          var data = imgData.data;

          // Put the modified image data back on the canvas
          ctx.putImageData(imgData, 0, 0);

          if (wall0 != 'none') {

            console.log('CHANGING');
            console.log(wall0);

            var leftwall = new Image();
            leftwall.src = wall0;
            
            leftwall.onload = function() {
              for (var i = 0; i < data.length; i += 4) {
                if (data[i] > 217 && data[i] <= 225 && data[i + 1] > 167 && data[i + 1] < 173 && data[i + 2] > 165 && data[i + 2] < 175) {
                  // Calculate the x and y position of the pixel
                  var x = (i / 4) % img.width;
                  var y = Math.floor((i / 4) / img.width);

                  // Scale the replacement image to match the size of the original image pixel
                  var scaledWidth = 0.5;
                  var scaledHeight = 1;
                  ctx.drawImage(leftwall, x, y, 1, 10, x, y, scaledWidth, scaledHeight);
                }
              }
            };

          }


        };

This code is hosted and running on “smamarble.com/room1“, feel free to try it. The concept is to select a wall and then select a panel (marble [image]) from the right side to display it on the wall, but again like I mentioned some images work (Kinda) and some look zoomed in.

Zip files download in react

Can someone please let me know how can I handle a response type application/zip

On hitting the API, I am receiving something like this :
c97828d606ec/Addendums/FIAT (1) (2) (1) (3).png�{TA�&� ���Fo,xpw�Hpw���4�]4�7A�N�����ٙݳ}x��ջu��կ�Q��o^�a�������R��C�}��P�Z�-3W��Нd���^<_�i�/����;l4u�t����M-� �^�Np���^N��7j3�����IG-��������$��F���ᣬi�ck��}-J-�%����fJ�eo��*�%B�������fZ�$n�"����u�T�%] �vN6sNNNj~0;�d��o ��������

I am not sure how to download this as an zip file in my project can someone please let me know the ways to handle this.

Thank you so much for your time.

    const response = await downloadZipFiles(s3Keys);
            let blob = new Blob([response], { type: 'application/zip' });
            saveAs(blob, 'fileName.zip');

I tried using the above code but the file dowmloaded was corrupted.

How to open a new browser tab in the same window as the web application from which it is launched

From web app 1, hyperlink 1 is clicked to launch web app 2 in a new browser window. Web app 2 is a Spring Boot, Spring MVC app, which utilises Thymeleaf Templates. It displays hyperlink 2, which when clicked, opens a file for viewing in a new tab using _blank as the target This works fine, but the new tab is launched in the same window as app 1, which is a little confusing for the user. Ideally, the file should open in a new tab within the same window as app 2.

This is the code for hyperlink 2:

<a th:text="${'object_name'}"
   th:href="@{/content/{filename}(filename=${'object_name')})}"
   target="_blank">
</a>

My first attempt at a fix is pasted below. The behaviour remains unchanged:

<a th:text="${'object_name'}"
   th:href="@{/content/{filename}(filename=${'object_name')})}"
   onclick="window.open(this.href, '_blank'); return false;">
</a>

My second attempt at a fix is pasted below. The file now opens in the same Window as app 2, but unfortunately it does not open a new tab, it just replaces app 2 in the existing tab:

<a th:text="${'object_name'}"
   th:href="@{/content/{filename}(filename=${'object_name')})}"
   onclick="openInSameWindow(event)">
</a>

Function added to my JavaScript file:

function openInSameWindow(event) {
    event.preventDefault(); // Prevents the default link behavior
    
    // Get the URL from the hyperlink
    var url = event.target.href;
    
    // Open the URL in a new tab within the same window
    window.open(url, '_self');
  }

I would be very grateful for any advice or suggestions on this. Many thanks for reading.

Slideshow navigation arrow links not working

I am just getting started with programming and am building my own website in Kirby. I want to implement a carousel slider in my website and followed this tutorial (https://youtu.be/9HcxHDS2w1s). I did everything exactly as shown but I cannot click on my arrows and so the slides don’t change. Everything else looks to be fine, it’s just the links I think.

Here’s the html:

    <div class="carousel-h" data-carousel>
        <button class="carousel-button-h prev-h" data-carousel-button="prev-h">
        <img src="<?= url('assets/icons/button-prev.svg') ?>"></button>
        <button class="carousel-button-h next-h" data-carousel-button="next-h">
        <img src="<?= url('assets/icons/button-next.svg') ?>">
        </button>
        <ul data-slides> 
            <li class="slide-h" data-active>
                <img src="images/Fokuss_Poster_web.jpg" alt="">
            </li> 
            <li class="slide-h">
                <img src="images/Rebooth_mockup_prints_web.jpg" alt="">
            </li>  
            <li class="slide-h">
                <img src="images/Kushim_Thumbnail_web.jpg" alt="">
            </li>  
            <li class="slide-h">
                <img src="images/Savo_Mockup_web.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Foto_Zine_2Sem_12-web.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Subspace_Mockup_web_0.jpg" alt="">
            </li>
            <li class="slide-h">
                <img src="images/Zeitung_Vision_06-web.jpg" alt="">
            </li>
        </ul>
    </div>
</section>

This is the javascript:


buttons.forEach(button => {
    button.addEventListener("click",  () => {
        const offset = button.dataset.carouselButton === "next" ? 1 : -1
        const slides = button
        .closest("[data-carousel]")
        .querySelector("[data-slides]")

    const activeSlide = slides.querySelector("[data-active]")
    let newIndex = [...slides.children].indexOf(activeSlide) + offset
    if (newIndex < 0) newIndex = slides.children.length -1
    if (newIndex >= slides.children.length) newIndex = 0

    slides.children[newIndex].dataset.active = true
    delete activeSlide.dataset.active
    })
})

And the css:

.carousel-h {
    width: 100vw;
    height: 100vh;
    position: relative;
}

.carousel-h > ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

.slide-h {
    position: absolute;
    inset: 0;
    opacity: 0;
    transition: 200ms opacity ease-in-out;
    transition-delay: 200ms;
}

.slide-h > img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

.slide-h[data-active] {
    opacity: 1;
    z-index: 1;
    transition-delay: 0ms;
}

.carousel-button-h {
    position: absolute;
    background: transparent;
    z-index: 999;
    border: none;
    font-size: 3rem;
    top: 50%;
    transform: translateY(-50%);
    color: rgba(0, 0, 0, 1);
    border-radius: .25rem;
    padding: 0 .5rem;
}

.carousel-button-h.prev-h {
    left: 1rem;
}

.carousel-button-h.next-h {
    right: 1rem;
}

I did replace the arrows used in the tutorial with my own svgs and thought that could be a problem but I also tried it with the HTML code for arrows from toptal and that makes no difference.

I tried my best to find the mistake but can’t figure it out so I’d appreciate any help! Thanks!

POST an image from frontend using Nuxt3 (vue3) to backend Fastapi ISSUE

I have this example backend in Fastapi:

@router.post("/api/v1/upload")
def upload_file(file: UploadFile = File(...)):
    print(file)
    return 200

In the frontend I am not able to post the image successfully getting all the time 422 Unprocessable Entity.

<form @submit.prevent="handleUpload" class="space-y-6" >
   <div>
      <input type="file"  @change="handleFileInputChange" accept="image/jpeg, image/png, 
      image/jpg">
   </div>
<button type="submit">UPLOAD</button>

Script

async function  handleFileInputChange (event) {
        const formData = new FormData();
        formData.append("file", event.target.files[0])

and the POST part

async function handleUpload() {   
  
      const url = "http://0.0.0.0:8000/api/v1/upload"
      const requestOptions = {
            method: "POST",
            headers: {     
                'Content-Type': 'multipart/form-data'
            },
            body: { file: formdata.file },
                        
              
              
        }
        const data = await $fetch(url, requestOptions)

This is not working I have tried all options of Headers like ‘Accept’: ‘/‘,’Content-Type’: ‘undefined’,

I have tried this as well:

body: JSON.stringify({file: formdata.file})

Any help here? Probably is something fundamental that I am missing.

Set the value of select html element with multiple attribute programmatically

Context

<!--HTML-->
<select class="form-select mb-1" id="document-select" name="documents" multiple size="10">                                        
    <option class="document-option" value="1">20230308-seed-document-0</option>
    <option class="document-option" value="2">20230308-seed-document-1</option>
// JS
const documentSelectEl = document.getElementById("document-select");
form.addEventListener("submit", (event) => {
    documentSelectEl.selectedIndex = -1;
    documentSelectEl.value = ["1", "2"];
    console.log(documentSelectEl.value); // Empty string
    documentSelectEl.value = "1,2";
    console.log(documentSelectEl.value); // Empty string
}

Issue

I am trying to set the value of a select html element before form submission. My intention is to reset all selected option elements (documentSelectEl.selectedIndex = -1) – essentially ignoring them – and set the value of the select element directly.

The reason I am trying to achieve this is that the list of option elements is paginated. In other words, the currently selected set of option elements does not correspond to the full selection of the user.

I would like to pass the full set of selected values, which is retrieved from sessionStorage, either as an array or as a comma-separated string.

Neither of these options seem to work. I should note that looking at the value of the select element in the debugger, I always see a single value despite the multiple attribute. The value seems to correspond to the last selected option element. Does it mean that the only way to set the value of a select element with multiple attribute programmatically is by setting the desired option elements?

Hi! I have a list of songs, on click a song plays. But after the list of songs is filtered it plays wrong song

Fot instance, if user clicks on first song in filtered list it plays first song in unfiltered list.

The reason why the wrong song might play after the songs are filtered is because the HomeSongContainer component is using the musics prop to render the list of songs. The musics prop is set to the filtered list of songs, but the addSongToContext function is still using the allSongs array to get the index of the song to play. This means that the addSongToContext function is always playing the first song in the allSongs array, even if the user has filtered the list of songs.

The component works as follows:

•When the component mounts, it fetches the list of all songs from the API.

•The user can then search for songs by entering a search term in the search bar.

•The user can also filter the list of songs by artist, category, album, or language.

•When the user clicks on a song, it will be played.



import React, { useEffect, useState } from "react";

import { getAllSongs } from "../api";

import { actionType } from "../Context/reducer";

import { useStateValue } from "../Context/StateProvider";

import { SongCard } from "../components/DashboardSongs";

import  { default as MusicPlayer }  from "../components/MusicPlayer";

import Filter from "../components/Filter";

import SearchBar from "../components/SearchBar";

import Dashboard from "../components/Dashboard";

import { motion } from "framer-motion";

import axios from "../utils/axios";

let scroll = 0;

const Music = () => {

   const [

    {

      searchTerm,

      isSongPlaying,

      song,

      allSongs,

      artistFilter,

      filterTerm,

      albumFilter,

      languageFilter,

    },

    dispatch,

  ] = useStateValue();

  const [filteredSongs, setFilteredSongs] = useState(null);

  useEffect(() => {

    if (!allSongs) {

      getAllSongs().then((data) => {

        dispatch({

          type: actionType.SET_ALL_SONGS,

          allSongs: data.data,

        });

      });

    }

  }, []);

  useEffect(() => {

    if (searchTerm.length > 0) {

      const filtered = allSongs.filter(

        (data) =>

          data.artist.toLowerCase().includes(searchTerm) ||

          data.language.toLowerCase().includes(searchTerm) ||

          data.name.toLowerCase().includes(searchTerm) ||

          data.artist.includes(artistFilter)

      );

      setFilteredSongs(filtered);

    } else {

      setFilteredSongs(null);

    }

  }, [searchTerm]);

  useEffect(() => {

    const filtered = allSongs?.filter((data) => data.artist === artistFilter);

    if (filtered) {

      setFilteredSongs(filtered);

    } else {

      setFilteredSongs(null);

    }

  }, [artistFilter]);

  useEffect(() => {

    const filtered = allSongs?.filter(

      (data) => data.category.toLowerCase() === filterTerm

    );

    if (filtered) {

      setFilteredSongs(filtered);

    } else {

      setFilteredSongs(null);

    }

  }, [filterTerm]);

  useEffect(() => {

    const filtered = allSongs?.filter((data) => data.album === albumFilter);

    if (filtered) {

      setFilteredSongs(filtered);

    } else {

      setFilteredSongs(null);

    }

  }, [albumFilter]);

  useEffect(() => {

    const filtered = allSongs?.filter(

      (data) => data.language === languageFilter

    );

    if (filtered) {

      setFilteredSongs(filtered);

    } else {

      setFilteredSongs(null);

    }

  }, [languageFilter]);

  return (

    <div >

   

      <SearchBar />

      {searchTerm.length > 0 && (

        <p >

          Searched for :

          <span >

            {searchTerm}

          </span>

        </p>

      )}

      <Filter setFilteredSongs={setFilteredSongs} />

      <div >

        <HomeSongContainer musics={filteredSongs ? filteredSongs : allSongs} />

      </div> 

      

      <Dashboard/>

      

    </div>

  );

};

export const HomeSongContainer = ({ musics }) => { 

  const [{ isSongPlaying, song }, dispatch] = useStateValue();

  const addSongToContext = (index) => {

    if (!isSongPlaying) {

      dispatch({

        type: actionType.SET_SONG_PLAYING,

        isSongPlaying: true,

      });

    }

    if (song !== index) {

      dispatch({

        type: actionType.SET_SONG,

        song: index,

      });

    }

  };

  return (

    <>

      {musics?.slice(0, 3).map((data, index) => (

        <motion.div

          key={data._id}

          whileTap={{ scale: 0.8 }}

          initial={{ opacity: 0, translateX: -50 }}

          animate={{ opacity: 1, translateX: 0 }}

          transition={{ duration: 0.3, delay: index * 0.1 }}

            onClick={() => addSongToContext(index)}

        >

          <div >

            <motion.img

              whileHover={{ scale: 1.05 }}

              src={data.imageURL}

              alt=""

              style={{width:"40px", height:"40px"}}

            />

          </div>

          <p >

            {data.name.length > 25 ? `${data.name.slice(0, 25)}` : data.name}

            <span >

              {data.artist}

            </span>

          </p>

        </motion.div>

      ))}

    </>

  );

};

export default Music

Has anybody clue how to fix this? Appreciate any help!

offset or separate axis for multiple xAxis in apache echarts within the same category

I have the code below. I want to separate each bar within each category so they do not overlap. This code is definitely not working as intended. Could you please help to fix the code so I get the desired output?

<!DOCTYPE html>
<html>
  <head>
    <title>Apache ECharts - Multiple X-Axes with Separated Bars</title>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
  </head>
  <body>
    <div id="chart" style="width: 600px; height: 400px"></div>

    <script>
      const xAxisData1 = ["Category 1", "Category 2", "Category 3"];
      const xAxisData2 = ["Category A", "Category B", "Category C"];
      const xAxisData3 = ["Category X", "Category Y", "Category Z"];

      const seriesData1 = [100, 200, 150];
      const seriesData2 = [300, 150, 250];
      const seriesData3 = [50, 100, 200];

      const chart = echarts.init(document.getElementById("chart"));

      const options = {
        grid: [
          { left: 50, right: 10 }, // grid for the first x-axis
          { left: 150, right: 10 }, // grid for the second x-axis
          { left: 250, right: 10 }, // grid for the third x-axis
        ],
        xAxis: [
          {
            type: "category",
            data: xAxisData1,
            offset: 0, // no offset for the first x-axis
            axisLine: {
              onZero: false, // show the axis line on the zero position
            },
          },
          {
            type: "category",
            data: xAxisData2,
            offset: 40, // some offset for the second x-axis
            axisLine: {
              onZero: false, // show the axis line on the zero position
            },
          },
          {
            type: "category",
            data: xAxisData3,
            offset: 80, // more offset for the third x-axis
            axisLine: {
              onZero: false, // show the axis line on the zero position
            },
          },
        ],
        yAxis: {},
        series: [
          {
            type: "bar",
            data: seriesData1,
            xAxisIndex: 0,
            barWidth: `${50 / xAxisData1.length}%`,
            barGap: `-100%`,
            barCategoryGap: "20%",
            itemStyle: {
              color: "#c23531", // red color for the first series
            },
          },
          {
            type: "bar",
            data: seriesData2,
            xAxisIndex: 1,
            barWidth: 20, // set the bar width to 20px
            barGap: "10%",
            barCategoryGap: "20%",
            itemStyle: {
              color: "#2f4554", // blue color for the second series
            },
          },
          {
            type: "bar",
            data: seriesData3,
            xAxisIndex: 2,
            barGap: "10%",
            barCategoryGap: "20%",
            itemStyle: {
              color: "#61a0a8", // green color for the third series
            },
          },
        ],
      };

      chart.setOption(options);
    </script>
  </body>
</html>

The current output?
enter image description here

Checking if promise chain is pending – react state is not updated

I’ve made promise chain for my fetch requests since I needed for each request to be sent after previous one is fulfilled.

My code is looking something like this :

const [requestQueue, setRequestQueue] = useState(Promise.resolve());

[...]

const requestFn = async () => {
return fetch([...]);
}

// When request is sent :

setRequestQueue(requestQueue.then(async () => {
    await requestFn();
}))

Now I need to implement functionality that prevents user from exiting website whenever fetching queue is still pending.

I’ve found somewhere on the internet following function that allows me to check whether promise has been fulfilled/rejected or is still pending :

function MakeQueryablePromise(promise) {
  // Don't modify any promise that has been already modified.
  if (promise.isFulfilled) return promise;

  // Set initial state
  var isPending = true;
  var isRejected = false;
  var isFulfilled = false;

  // Observe the promise, saving the fulfillment in a closure scope.
  var result = promise.then(
    function (v) {
      isFulfilled = true;
      isPending = false;
      return v;
    },
    function (e) {
      isRejected = true;
      isPending = false;
      throw e;
    }
  );

  result.isFulfilled = function () {
    return isFulfilled;
  };
  result.isPending = function () {
    return isPending;
  };
  result.isRejected = function () {
    return isRejected;
  };
  return result;
}

Now I’m trying to make a state that will be tracking whether requestQueue is pending :

const [requestQueueCheck, setRequestQueueCheck] = useState(MakeQueryablePromise(requestQueue));

[...]

useEffect(() => {
    setRequestQueueCheck(MakeQueryablePromise(requestQueue));
  }, [requestQueue]);

And when I’m trying, for example, to display a spinner while fetching is in progress :

[...]

return (
<div>
  {requestQueueCheck.isPending() && <Spinner />}
</div>
)

My problem is that my component doesn’t re-render automatically after fetch is fulfilled, causing the spinner to appear until I re-render the component manually (for ex. by clicking on the page).

  1. Before fetching anything requestQueueCheck.isPending() === false (correctly)
  2. Fetch request is sent, requestQueueCheck.isPending() === true (correctly)
  3. Fetch request is fulfilled, requestQueueCheck.isPending() in my component doesn’t change to false until component is re-rendered “manually”, for ex. by clicking on the page. (wrong behavior, I want it to change to false (re-render) automatically)

Openlayers getFeatureById gives null

I faced the following problem: I compiled a usefull map with own generated geojson data, that’s work fine. Now I want to make summary box next to the map, the data for summary text is from the same geojson file with specific id (and fictitious coords) to reach them. So, I try to reach them with “getFeatureById”, but it throws null…

Snippet from the geojson file (the first paragraph is data for summary text, the next paragraph is conventional geojson data):

{ "type": "FeatureCollection", "features": [
{"type": "Feature", "geometry": { "type": "Point", "coordinates":  [0,0] }, "properties": { "id":"node/BP", "ossz_tervkoltseg":"9045.1", ... } },

{"type": "Feature", "geometry": { "type": "Point", "coordinates":  [19.0908557,47.5269017] }, "properties": { "id":"node/8420278688", "ossz_tervkoltseg":"370.5", ... } },
...

My script:

const map = new ol.Map({
 view: new ol.View({ center: [2164846.200859313,5963803.432942492], zoom: 7.5}),
 layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ],
 target: 'js-map' });

const prbGeoJSON = new ol.layer.VectorImage({
 source: new ol.source.Vector({ url: "./mli.geojson", format: new ol.format.GeoJSON() }),
 visible: true,
 title: "prbGeoJSON",
 style: function(feature, resolution){ ... } });

map.addLayer(prbGeoJSON); // it works fine so far
                        
map.once('postrender', function(event) {
 let feature = prbGeoJSON.getSource().getFeatureById("node/BP");        
 console.log(feature); // throw null...
});

What have I done wrong?

Mongoose:Error when send a second request on the server

I’m making an API for my app, the app is in MERN stack, I make a separate Database for every account and its information (every account along with it’s info is in a separate DB so each DB for each account)

I have a middleware which runs on every request and decrypts the auth-token retrieves the user’s DB name and connects to the DB

It works fine the first time I send a request, but gives this error second time I send a request (the middleware name is connectToDB)

The Error:

MongooseError: Connection was force closed
at NativeCollection. [as findOne]

the error is causing at this line

const company = await Company.findById(data.company).select("-password")

my middleware:

const jwt = require('jsonwebtoken');
const JWT_SECRET = "PASSjajghjklnaslg"
const Company = require("../models/Company");
const mongoose = require("mongoose");
const Admin = require('../models/Admin');
const Employee = require('../models/Employee');
const Manager = require('../models/Manager');
const SubAdmin = require('../models/SubAdmin');
const URI = "mongodb://0.0.0.0:27017/";

const connectToDB = async (req, res, next) => {
    const token = req.header("auth-token");

    if (!token) {
        next()
        return
    }
    try {
        const data = jwt.verify(token, JWT_SECRET);
        let Account;

        const dbName = data.companyEmail.replace(/[.]/g, '%2e')

        const adminDb = mongoose.connection.db.admin();
        const result = await adminDb.listDatabases();
        const dbsNames = result.databases.map(db => db.name);

        if (!dbsNames.includes(dbName)) {
            res.status(401).send("Access denied");
            return
        }
        await mongoose.disconnect()
        await mongoose.connect(`${URI}${encodeURIComponent(dbName)}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })

        if (data.accountType == "company") {
            const company = await Company.findById(data.company).select("-password")
            const anyDoc = await Company.findOne({})

            if (!company && !anyDoc) {
                await mongoose.connection.db.dropDatabase()
                res.status(401).send("Access denied");
                return
            }
            if (!company) {
                res.status(401).send("Access denied");
                return
            }

            res.locals.company = company

            next()
            return
        } else if (
            data.accountType == "admin" ||
            data.accountType == "subAdmin" ||
            data.accountType == "manager" ||
            data.accountType == "employee"
        ) {

            if (req.query.role == "admin") {
                Account = Admin;
                accountType = "admin"
            } else if (req.query.role == "subAdmin") {
                Account = SubAdmin;
                accountType = "subAdmin"
            } else if (req.query.role == "manager") {
                Account = Manager;
                accountType = "manager"
            } else if (req.query.role == "employee") {
                Account = Employee;
                accountType = "employee"
            } else {
                return res.status(400).send("Invalid role")
            }

            const account = await Account.findById(data.user).select("-password")

            if (!account) {
                res.status(401).send("Access denied");
                return
            }

            res.locals.company = account

            next()
            return
        } else {
            return res.status(400).send('bad request')
        }


    }
    catch (err) {

        console.log(err)

        res.status(401).send({
            errors: [
                "Access denied"
            ]
        })

        return
    }
}

module.exports = connectToDB;

How do I send the selected image’s base64 to the freeimage.host api in my JS code?

I am new to JS & am trying to make a webpage which has a button which receives an image url from my app and shows it. when the button is clicked, user gets to click the button and replace the image inside it by selecting one from their phone, which then should go to the freeimage.host api and in response i get the hosted url which I send back to my app.

Here’s the relevant js part of my code which is supposed to let the user replace the existing image in the button and when new image is selected, send the POST request to that api to upload –

    document.getElementById("image-upload").addEventListener("change", function(event) {
      const file = event.target.files[0];
      const reader = new FileReader();

      reader.onload = function(e) {
        const uploadedImage = document.createElement("div");
        uploadedImage.classList.add("uploaded-image");
        uploadedImage.style.backgroundImage = `url(${e.target.result})`;

        const existingImage = uploadButton.querySelector(".uploaded-image");
        if (existingImage) {
          uploadButton.removeChild(existingImage);
        }

        uploadButton.appendChild(uploadedImage);

        ThunkableWebviewerExtension.postMessage("Sending...");

        const data = {
          key: "<MY_API_KEY>",
          action: "upload",
          source: e.target.result,
          format: "json"
        };

        fetch("https://freeimage.host/api/1/upload/", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(data)
        })
          .then(response => response.json())
          .then(data => {
            const imageUrl = data.image.url;
            ThunkableWebviewerExtension.postMessage(imageUrl);
          })
          .catch(error => {
            ThunkableWebviewerExtension.postMessage("Error uploading image: " + error);
          });
      };

      reader.readAsDataURL(file);
    });

What’s going wrong is I think I am failing to correctly integrate the api & am incorrectly sending the parameters requested, so i’m repeatedly getting “Typeerror : failed to fetch”. What is it I am doing wrong here? I just want to send the selected image’s base64 format to the api using a POST request. Also, I know the typeerror isn’t related to CORS, as there’s one more api I am using in this code which is also a POST request and it works fine (or that is not how it works?)…

Here’s the api documentation link (https://freeimage.host/page/api), which says to add these parameters and send the post request –

Can someone advice on how should I implement this correctly? Thanks!