Getting POST 500 Internal server error while sending request via ajax call

I have a logic where I want to insert data into database. SO I am sending ajax request through my local machine. Below is the code for the same..

$("#btnSubmitCT").on('click', function () {       

        var valid = validateForm();
        if (valid) {
            $("#divLoadingPanel").show();
            SubmitForm_CE().done(function () {
                $("#divLoadingPanel").hide();
            });
        }

    });
    
    
function SubmitForm_CE() {
    try {

        var req_id = "";
        var umsGroupNameBy = CurrentGroupName;
        var umsGroupIdBy = CurrentGroupID;
        var loginUserName = LoginUserName;
        var spanType = $(spantypeid + ' option:selected').val().toUpperCase();
        var r4gState = $(r4gstatediv + ' option:selected').text();
        var UG_LEN = parseFloat($('#UGLEGCE_txt').html()).toFixed(4);
        var AR_LEN = parseFloat($('#ARLEGCE_txt').html()).toFixed(4);

        var fixedUG = parseFloat($('#UGLEGCE_txt').html()).toFixed(4);
        var fixedAR = parseFloat($('#ARLEGCE_txt').html()).toFixed(4);

        var linkId;
        var spanId;
        var createdId;
        if (spanType == AppConfig.SpanTypeInter.toUpperCase()) {
            linkId = "";
            spanId = $(spnLinkId).text();
            createdId = "SPAN ID: " + spanId;
        }
        else {
            spanId = "";
            linkId = $(spnLinkId).text();
            createdId = "LINK ID: " + linkId;
        }

        var mZoneCode = $(mzoneid + ' option:selected').val();
        var mZoneText = $(mzoneid + ' option:selected').text();
        var mZoneArr = mZoneText.split('/');
        var mZoneName = mZoneArr[0];
        var operationType = $(activitytypeid + ' option:selected').val().toUpperCase();

        var pendSpanLeg = parseFloat($(pendingSpanLen).html());
        var neLeg = parseFloat($(spnspanlength).html());        
        var offerHoto = parseFloat($(hotoofferbyct).val());
        var offerDate = $('#ctOfferdatepicker').val();
        
        var remark = $(remarkct).val();
        var offerValue = JSON.stringify({ "OFFERHOTO": offerHoto, "OFFERLIT": "0", "NE_LEG": neLeg, "HOTOCOMPLETED": "0", "LITCOMPLETED": "0" });
        var statusId = getHotoStatusID(offerValue);
        var umsGroupObj = JSON.parse(UMSGroupDetails)
        var GroupToValue = "";
        var umsGroupNameTo = "";
        var umsGroupIdTo;
        $.each(umsGroupObj, function (index, element) {
            if (element.GroupName == UserGrouop.FE) {
                umsGroupNameTo = element.GroupName;
                umsGroupIdTo = element.GroupID;
            }
        });
        var Values = { "SPANID": spanId, "LINKID": linkId, "CREATEDBY": loginUserName, "MZONECODE": mZoneCode, "MZONENAME": mZoneName, "NELEG": neLeg, "UGLEG": UG_LEN, "ARLEG": AR_LEN, "STATUSID": statusId, "HOTOOFFERDATE": offerDate, "REMARK": remark, "HOTOOFFERLEG": offerHoto, "UMSGROUPIDBY": umsGroupIdBy, "UMSGROUPNAMEBY": umsGroupNameBy, "UMSGROUPIDTO": umsGroupIdTo, "UMSGROUPNAMETO": umsGroupNameTo, "SPANTYPE": spanType, "R4GState": r4gState };

        return $.ajax({
            type: "POST",
            url: AppConfig.PrefixURL + "App/InitiateWF_CT",
            data: JSON.stringify(Values),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            //            async: false,
            beforeSend: function () {
            },
            success: function (response) {
                alert(response);
                var datalist = JSON.parse(response);
                var state = datalist.split('|')[0];
                var msg = "";
                if (state == "SUCCESS") {
                    msg = "Request Id: " + datalist.split('|')[1] + " has been created for " + createdId;
                    req_id = datalist.split('|')[1];                    
                    hideInfoWindow();                    
                    hideLoading();
                    jAlert(msg, ValidationMessageConfig.Title, function () {
                        $(spandetailsdiv).hide();
                        deleteSpanListDatatable_CT($(spnLinkId).text());
                    });

                } else if (state == "WARNING" || state == "EXISTS") {
                    msg = datalist.split('|')[1];
                    hideInfoWindow();
                    hideLoading();
                    jAlert(msg, ValidationMessageConfig.Title, function () {
                        $(spandetailsdiv).hide();
                        deleteSpanListDatatable_CT($(spnLinkId).text());
                    });
                } else {
                    hideLoading();
                    msg = datalist.split('|')[1]
                    jAlert(msg, ValidationMessageConfig.Title, function () {
                        $(spandetailsdiv).hide();
                        deleteSpanListDatatable_CT($(spnLinkId).text());
                    });
                    AppLog.getLogger('error', "Error occured during processing new job");
                }
            },
            error: function (response) {
               // jAlert(ErrorMessageForMethods.initiateWF, ErrorMessageForMethods.Title);
                //AppLog.getLogger('error', "Error occured during processing new job");
                // hideLoading();
                alert('NO Record created 1');
                hideLoading();
            }
        });
    } catch (e) {
        $(spandetailsdiv).hide();
        hideLoading();
        alert('NO Record created 2');
        //jAlert(ErrorMessageForMethods.initiateWF, ErrorMessageForMethods.Title);
        //AppLog.getLogger('error', "Error occured during processing new job");

    }
}    

url: AppConfig.PrefixURL + "App/InitiateWF_CT", here it is telling that http://localhost:2126/App/InitiateWF_CT 500 (Internal Server Error)

Can you suggest what is wrong in this ?

i want all images selected one by one with a click on image from html, how do i loop over them in javascript?

I am building a memory game and want to loop through all images one by one in javascript.
The idea is to put it in the ImageUrl variable i have made connected to the newCard variable and loop over every image one by one by click on html image.

I’ve tried to research it but can’t find any answers.

This is what i have for code:

function populateField() {
    for (let i = 0; i < myCardSet.length; i++) {
        let newTile = document.createElement('div');
        let newCard = document.createElement('img');
        let imageURL = document.getElementById('field').getElementsByTagName('img')
    for (let i of imageURL) {
        let ImageSrc = i.getAttribute('name')
        console.log(ImageSrc.substring(ImageSrc.lastIndexOf('/') + 1))
    }
        newCard.setAttribute('src', imageURL)
        newCard.setAttribute('name', imageURL)
        newTile.appendChild(newCard)
        myField.appendChild(newTile)
        let img = {
            src: 'cover.png',
            class: '.covered'
        }
    }
}
<body>

    <div id="field"><img src="../begin/img/calf.jpg" alt="" name="calf">
        <img src="../begin/img/cat.jpg" alt="" name="cat">
        <img src="../begin/img/chick.jpg" alt="" name="chick">
        <img src="../begin/img/cow.jpg" alt="" name="cow">
        <img src="../begin/img/dog.jpg" alt="" name="dog">
        <img src="../begin/img/duck.jpg" alt="" name="duck">
        <img src="../begin/img/goat.jpg" alt="" name="goat">
        <img src="../begin/img/goose.jpg" alt="" name="goose">
        <img src="../begin/img/hen.jpg" alt="" name="hen">
        <img src="../begin/img/horse.jpg" alt="" name="horse">
        <img src="../begin/img/kitten.jpg" alt="" name="kitten">
        <img src="../begin/img/lamb.jpg" alt="" name="lamb">
        <img src="../begin/img/pig.jpg" alt="" name="pig">
        <img src="../begin/img/piglet.jpg" alt="" name="piglet">
        <img src="../begin/img/puppy.jpg" alt="" name="puppy">
        <img src="../begin/img/rooster.jpg" alt="" name="rooster">
        <img src="../begin/img/sheep.jpg" alt="" name="sheep">
        <img src="../begin/img/veal.jpg" alt="" name="veal">
        <img src="../begin/img/cat.jpg" alt="" name="cat">
        <img src="../begin/img/chick.jpg" alt="" name="chick">
        <img src="../begin/img/cow.jpg" alt="" name="cow">
        <img src="../begin/img/dog.jpg" alt="" name="dog">
        <img src="../begin/img/duck.jpg" alt="" name="duck">
        <img src="../begin/img/goat.jpg" alt="" name="goat">
        <img src="../begin/img/goose.jpg" alt="" name="goose">
        <img src="../begin/img/hen.jpg" alt="" name="hen">
        <img src="../begin/img/horse.jpg" alt="" name="horse">
        <img src="../begin/img/kitten.jpg" alt="" name="kitten">
        <img src="../begin/img/lamb.jpg" alt="" name="lamb">
        <img src="../begin/img/pig.jpg" alt="" name="pig">
        <img src="../begin/img/piglet.jpg" alt="" name="piglet">
        <img src="../begin/img/puppy.jpg" alt="" name="puppy">
        <img src="../begin/img/rooster.jpg" alt="" name="rooster">
        <img src="../begin/img/sheep.jpg" alt="" name="sheep">
        <img src="../begin/img/veal.jpg" alt="" name="veal">
    </div>

    <script src="js/memory.js" type="module"></script>
</body>

Please help,
Thanks already!

My frontend is unable to connect to the backend address

“My frontend can’t connect to the backend address, but I can make a POST request with curl. Here is the browser error: net::ERR_CONNECTION_REFUSED at (index):9 when trying to POST to http://127.0.0.1:5000/process-data.”
Front-end code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
<script>
function sendData() {
    // Make sure the URL is the Flask application address, usually http://127.0.0.1:5000/process-data if it's local
    fetch('http://127.0.0.1:5000/process-data', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({message: 'Hello, backend!'}),
    })
    .then(response => response.json())
    .then(data => {
        // Display the data returned from the backend on the webpage
        document.getElementById('response').innerText = data.reply;
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}
</script>
</head>
<body>

<button onclick="sendData()">Send data to backend</button>
<div id="response">The response from the backend will be displayed here.</div>

</body>
</html>

Back-end code:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/process-data', methods=['POST'])
def process_data():
    # Retrieve the data sent from the front-end
    data = request.json
    print(data)  # Just as an example, the data might need to be processed in a real application

    # Suppose this is the response after processing
    reply = {'reply': f"Backend received your message: {data.get('message')}"}

    # Return the processed result to the front-end
    return jsonify(reply)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

This translation includes the comments within the code for clarity.

I’ve been trying to enable interaction between the front end and the back end to create a website.

Rehype to render hashtag as url

Trying to make a something like #tag render as a URL the markdown editor MDEditor using rehypeRewrite. Here’s what I have so far

const REG = /B(#[a-zA-Z]+b)(?!;)/gi;

<MDEditor 
    style={{width: "100%", height: "100%"}} 
    minHeight={500} 
    value={value} 
    onChange={(event) => {
        setValue(event || '');
    }} 
    previewOptions={{
        rehypePlugins: [
            [
            rehypeRewrite,
            {
                rewrite: (node : any, index: any, parent: any) => {
                if (node.type === "element" && node.tagName === "p") {
                    let text = getCodeString(node.children);
                    if (REG.test(text)) {
                        node.children = [
                        {
                            type: 'link',
                            url: 'https://example.com',
                            children: [{type: 'text', value: text} ]
                        }];
                    }
                }}
            },
        ]],
    }}
/>

The regex properly matches the text but instead of the node being replaced with a link, it just doesn’t render anything.

Any guidance on what I may be doing wrong would be much appreciated

Svelte how to have duplicate keys in a keyed each

I have a simple clicker app, that stores the number as a list (500 being [5,0,0]). Here’s my current implementation:

{#each numbers as number (number)}
    <h1 class="score-text">{number}</h1>
{/each}

It can count up to 10, but 11 won’t work as they are the same number.

each.js:135  Uncaught (in promise) Error: Cannot have duplicate keys in a keyed each: Keys at index 0 and 1 with value '1' are duplicates
    at validate_each_keys (each.js:135:10)
    at Object.update [as p] (ScoreCounter.svelte:13:23)
    at update (scheduler.js:119:30)
    at flush (scheduler.js:79:5)

What could I do to fix this?

Just placing a bunch of elements with numbers[0] through numbers[15] works, but I feel like there must be a better way.

Best Way to Convert js object

I try to Upload Files with Ajax Post and form.serialize, but my req.body looks like this:

    {
    _uploadFilesMessage: '',
    mailgroupIDS: '',
    'field[0][fileID]': '0',
    'field[0][filename]': 'img_nature_wide27.jpg',
    'field[0][filetype]': '2',
    'field[0][selTag]': '322444370236',
    'field[1][fileID]': '1',
    'field[1][filename]': 'img_snow_wide10.jpg',
    'field[1][filetype]': '2',
    'field[1][selTag]': '322444370236'
  }

but i need it like this:

{
  _uploadFilesMessage: '',
  mailgroupIDS: '',
  field: [
    {
      fileID: '0',
      filename: 'img_nature_wide27.jpg',
      filetype: '2',
      selTag: '322444370236'
    },
    {
      fileID: '1',
      filename: 'img_snow_wide10.jpg',
      filetype: '2',
      selTag: '322444370236'
    }
  ]
}

What is the most efficient way to convert the req.body ?

Returning value from apps script (doPost) to client, after calling an external API

I am trying to invoke an apps script deployed web app (doPost method) and get a response back to the client app (this could be HTTP client like Postman/Bruno or simple javascript app).
The deployed web app would call an external API and return its result.
When I try this I am getting a message (HTML) saying “The script completed but the returned value is not a supported return type.”
If I do not call external API and try to return a default / hard coded object from doPost, the client is getting the response properly (as a JSON).
Console log statements are showing proper output values
Please suggest if there is a way out.

Deployed web app (apps script) is

let respout= { "jokeid": 0, "errcode": 0, "errmsg": "na" };
function doPost() 
{
    console.log('inside doPost func', respout);
    try 
      {  //If tried to return above respout with out executing "jokefun()", below statement works with client
         //return ContentService.createTextOutput(JSON.stringify(respout)).setMimeType(ContentService.MimeType.JSON);
         return jokefunc().then( res => {
                                          respout={ "jokeid": res.id,"errcode": 200,"errmsg": "success" };
                                          console.log('resp out val in then func',respout);
                                          return ContentService.createTextOutput(JSON.stringify(respout)).setMimeType(ContentService.MimeType.JSON);
                                        })
        
      } 
    catch (error) 
      {
        console.log('Exception in doPost', error);
      }
    
}

async function jokefunc() 
{
  try
    {
      const API_URL = "https://official-joke-api.appspot.com/random_joke";
      const response = UrlFetchApp.fetch(API_URL);
      const responseText = response.getContentText();
      const jsonData = JSON.parse(responseText);
      console.log('Fetch called', jsonData);
      return jsonData; // Return the fetched data object
    }
  catch(error)
    {
      console.error('Some thing went wrong',error)
    }
}

Reading the user’s console errors from a chrome extension

I am creating a small extension for personal use that should help me analyze errors using an API I made. In order to do that it requires read access to the console of the active tab. Is there a way to achieve that? I tried overriding the console methods but then found out the extension’s js is isolated from the tab’s, so kinda lost here.

Any help would be much appreciated, thanks in advance.

Making a fade in when in sight thing but it messed up my :hover effect for a card thing

I have 8 divs in a div called card-group these cards should expand and there are also little cards which go to the edge this worked then a added more text at the bottom and the on screen fade in but it messed up the :hover effect.
Here is one of the :hover statements there are 8 of these:
style.css

.card-group:hover  .big-card:nth-child(1) {
  transform: translate(-75%,16%) rotate(-24deg);
  cursor: pointer;
}

then theres also the seen part in style.css

.hidden {
  opacity: 0;
  transition: all 1s;
  filter: blur(5px);
  transform: translateX(-100%);
}
.visible {
  opacity: 1;
  filter: blur(0px);
  transform: translateX(0);
}

Here is the code from app.js with a defer propertie

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) =>{
    if (entry.isIntersecting) {
      entry.target.classList.add('visible'); // Use a different class for visibility
    } else {
      entry.target.classList.remove('visible');
    }
  });
});

const hiddenElements = document.querySelectorAll('.hidden');
hiddenElements.forEach((element) => observer.observe(element));

const cards = document.querySelectorAll('.card');

cards.forEach(card => {
  card.addEventListener('mouseenter', () => {
    card.classList.add('hovered');
  });

  card.addEventListener('mouseleave', () => {
    card.classList.remove('hovered');
  });
});

I was expecting this card group to open like the 8 :hover things said it should but instead it just did nothing the effect where the hidden and visible things fade in works but the hover does not. Thanks in advance if there was a way I could have written this better please let me know.

Unable to find DOMelements email and password field through Cypress

I am trying to login to this page https://eddui–preprod2.sandbox.my.site.com/s/scplogin?language=en_US&redirectUrl=https%3A%2F%2Ficampp.edd.ca.gov%2Fhome%2Fcaeddicamext_uiostgrf_1%2F0oa6gj2jlz4J3AlIE1d7%2Faln6gj88wtdBQHuBn1d7

and trying to login through the DOM element’s Email and Password field but Cypress is unable to find the email and password fields

Here is the code:

describe(‘add function’, () => {
// This is a suite of tests for the add function

it(‘Should Login to Eddui’, () => {
cy.visit(‘https://eddui–preprod2.sandbox.my.site.com/s/scplogin?language=en_US&redirectUrl=https%3A%2F%2Ficampp.edd.ca.gov%2Fhome%2Fcaeddicamext_uiostgrf_1%2F0oa6gj2jlz4J3AlIE1d7%2Faln6gj88wtdBQHuBn1d7’)
cy.wait(6000)
cy.get(‘c-scp-login’)
cy.get(‘input[name=”password”]’).type(‘your_password’);
//cy.get(‘/html/body/div[3]/div[1]/div/div[2]/div/div/c-scp-login/div/div/div/div[2]/div/div[2]/div[1]/c-input-email/div/input’).type(‘[email protected]’)
})
})

Color Thresholding JS, Average Image Color Detect JS

I had watched the following tutorial https://youtu.be/BTWPDboW38o?si=_21TOjCfrXC3VWIL and tried the same. What I expect is, I want to change the background color of document based on the color of video stream. But it is always returning rgb(0,0,0).
`

‘use strict’;

try {

const w = window,

    d = document,

    ng = navigator,

    id = e => {

        return d.getElementById(e)

    },

    cn = id('lh'),

    i = id('i'),

    o = id('o'),

    cx = cn.getContext('2d', {

        willReadFrequently: true

    }),

    face = r => ng.mediaDevices.getUserMedia({

        video: {

            facingMode: {

                exact: 'user'

            }

        }

    }).then(s => {

        i.srcObject = s;

        i.onloadedmetadata = e => {

            setInterval(() => {

                let c = 0,

                    k = -4,

                    h = cn.height = i.videoHeight,

                    w = cn.width = i.videoWidth,

                    dt = cx.getImageData(0, 0, w, h),

                    io = dt.data,

                    dl = io.length,

                    R, G, B;

                R = G = B = 0;

                cx.drawImage(i, 0, 0, w, h);

                o.src = cn.toDataURL('image/webp');

                while ((k += r * 4) < dl) {

                    ++c;

                    R += io[k];

                    G += io[k + 1];

                    B += io[k + 2]

                };

                ['R', 'G', 'B'].forEach(e1 => {

                    eval(e1 + '=' + `~~(${e1}/c)`)

                });

                let rgb = `rgb(${R},${G},${B})`;

                d.body.style.background = rgb

            }, -1)

        }

    });

face(4)

} catch (e) {

alert(e)

}`

I expect it should change the background color of document based on video stream.

Jittery Behavior on First Scroll in React Header Component

Description

I’m encountering an issue with the header component in my React based next.js web application. Upon the initial load of the page, when I first scroll, there’s a noticeable jittery behavior before the header hides as intended. Once this initial jittery behavior occurs, the header behaves perfectly fine for subsequent scrolls.

function Header() {
    const [mounted, setMounted] = useState(false);
    const { theme } = useTheme();
    const [prevScrollPos, setPrevScrollPos] = useState(0);
    const [visible, setVisible] = useState(true);

    useEffect(() => {
        const handleScroll = () => {
            const currentScrollPos = window.scrollY;
            setVisible(prevScrollPos > currentScrollPos || currentScrollPos < 200);
            setPrevScrollPos(currentScrollPos);
        };

        window.addEventListener("scroll", handleScroll);

        return () => window.removeEventListener("scroll", handleScroll);
    }, [prevScrollPos]);

    useEffect(() => {
        setMounted(true);
    }, []);

    if (!mounted) {
        return null;
    }

    return (
        <>
            {(theme === 'light' || theme === 'undefined' || theme === null) && visible && <LightHeader />}
            {theme === 'dark' && visible && <DarkHeader />}
        </>
    )
}

(I am using next-themes for theme switching. The mounting logic is to mitigate hydration error)

I suspect I might be missing a crucial React concept or best practice here. Could someone please provide insights into what might be causing this jittery behavior on the first scroll and how I can resolve it? Would de-bouncing help in this scenario? Additionally, could this issue be related to React Snapshot?

Any help or guidance would be greatly appreciated! Thank you.

Getting a wrong value while converting date from german locale to english using moment

All I want is to get the date value received in german language to english format for which i tried using moment library as given below

It does convert but unfortunately returns a wrong value.

moment('Mär 29, 2024', 'MMM DD, YYYY', 'de-DE').locale('en-US').format('MM/DD/YYYY')

// Expected Value - 03/29/2024
// received value - 01/29/2024

Is there a fix for this ?

Slim routing in PHP-DI container

I’m moving a project of mine into Slim Microframework, by using PHP-DI containerization.
I need to POST some JSON data to http://localhost/api/base (XAMPP) and get a confirmation (at least at the beginning).
This is my index.php:

<?php

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;
use SlimExceptionHttpMethodNotAllowedException;
use SlimExceptionHttpNotFoundException;
use SlimRoutingRouteContext;
use DIContainerBuilder;

// Set error reporting to display all errors
error_reporting(E_ALL);
ini_set('display_errors', 'On');

// Autoloading using Composer's autoload
require __DIR__ . '/../vendor/autoload.php';

// Include dependencies file
$container = require_once __DIR__ . '/../config/dependencies.php';

// Create Slim app
$app = AppFactory::create();

// Include routes
require __DIR__ . '/../src/routes.php';

$app->run();

This is routes.php:

<?php

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use AppControllersHotelBaseController;

// Include dependencies file
$container = require_once __DIR__ . '/../config/dependencies.php';

// Define basic route
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write('Hello, World!');
    return $response;
});


// Route for handling POST request to /api/base
$app->post('/api/base', function (Request $request, Response $response) use ($container) {
    // Get the HotelBaseController service from the container
    $hotelBaseController = $container->get('HotelBaseController');

    // Call the handlePostRequest method
    return $hotelBaseController->handlePostRequest($request, $response);
});


$app->get('/api/base/', function (Request $request, Response $response) {
    return $response->withStatus(301)->withHeader('Location', '/api/base');
});

This is the dependencies.php:

<?php

use DIContainerBuilder;
// use PsrHttpMessageResponseInterface as Response;
// use PsrHttpMessageServerRequestInterface as Request;

require __DIR__ . '/../vendor/autoload.php';

// Create ContainerBuilder instance
$containerBuilder = new ContainerBuilder();

// Set up your container configuration
$containerBuilder->addDefinitions([
    'HotelBaseController' => DIcreate(AppControllersHotelBaseController::class),
]);

// Build the container
return $containerBuilder->build();

And, finally, this is hotelBaseController.php:

<?php

namespace AppControllers;

use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;

class HotelBaseController {
    public function handlePostRequest(Request $request, Response $response) {
        // Get the JSON data from the request body
        $data = $request->getParsedBody();

        // You can access the individual fields from the JSON data
        $userId = $data['userId'] ?? '';
        $apiKey = $data['apiKey'] ?? '';
        $documentType = $data['document_type'] ?? '';
        $hotelId = $data['hotel_id'] ?? '';
        $hotelName = $data['name'] ?? '';

        $res = 'Who knows';
        
        return $res;
    }
}

?>

When sending any POST request, containing a simple JSON, I get the error:

<b>Fatal error</b>: Uncaught Error: Call to a member function get() on bool in C:xampphtdocssrcroutes.php:20
Stack trace:
#0 C:xampphtdocsvendorslimslimSlimHandlersStrategiesRequestResponse.php(38):
{closure}(Object(SlimHttpServerRequest), Object(SlimHttpResponse), Array)
#1 C:xampphtdocsvendorslimslimSlimRoutingRoute.php(358):
SlimHandlersStrategiesRequestResponse-&gt;__invoke(Object(Closure), Object(SlimHttpServerRequest),
Object(SlimHttpResponse), Array)
#2 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimRoutingRoute-&gt;handle(Object(SlimHttpServerRequest))
#3 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#4 C:xampphtdocsvendorslimslimSlimRoutingRoute.php(315):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#5 C:xampphtdocsvendorslimslimSlimRoutingRouteRunner.php(68):
SlimRoutingRoute-&gt;run(Object(SlimHttpServerRequest))
#6 C:xampphtdocsvendorslimslimSlimMiddlewareDispatcher.php(65):
SlimRoutingRouteRunner-&gt;handle(Object(SlimHttpServerRequest))
#7 C:xampphtdocsvendorslimslimSlimApp.php(199):
SlimMiddlewareDispatcher-&gt;handle(Object(SlimHttpServerRequest))
#8 C:xampphtdocsvendorslimslimSlimApp.php(183): SlimApp-&gt;handle(Object(SlimHttpServerRequest))
#9 C:xampphtdocspublicindex.php(50): SlimApp-&gt;run()
#10 {main}
thrown in <b>C:xampphtdocssrcroutes.php</b> on line <b>20</b><br />

I would like to understand where am I making a mistake.
Thanks