How to determine whether to use query parameters or body in GET requests when integrating with different APIs?

I am working with two different APIs, both using GET requests but handling request data differently:

  1. API 1 requires the data to be sent in the request body, even though the HTTP method is GET.
    Example:

    $config = [
        'method' => 'GET',
        'url' => 'http://example.com/api/endpoint',
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'body' => [
            'key1' => 'value1',
            'key2' => 'value2',
        ],
    ];
    
  2. API 2 requires the data to be sent as query parameters in the URL.
    Example:

    $config = [
        'method' => 'GET',
        'url' => 'http://example.com/api/endpoint',
        'headers' => [
            'Content-Type' => 'application/json',
        ],
        'query' => [
            'key1' => 'value1',
            'key2' => 'value2',
        ],
    ];
    

Both APIs work with the GET method, but their requirements for passing data are different. This makes it challenging to decide when to use query parameters and when to use the request body for a GET request.

Questions:

  1. How can I determine whether to use query parameters (query) or the request body (body) for a GET request?
  2. Is it common or correct for a GET request to accept data in the body, even though the HTTP specification discourages it?
  3. How can I design a generic HTTP client (e.g., using Guzzle) to handle these differences dynamically based on the API’s requirements?

Any guidance, best practices, or examples would be appreciated!

 $options = ['headers' => $request['headers']];

        if ($request['method'] === 'GET') {
            if ($request['isRequestRawBody']) {
                $options['body'] = json_encode($request['body']);
            } else {
                $options['query'] = $request['body'];
            }
        } else {
            $contentType = $request['headers']['Content-Type'] ?? '';

            switch ($contentType) {
                case 'application/x-www-form-urlencoded':
                    $options['form_params'] = $request['body'];
                    break;
                case 'application/json':
                    $options['json'] = $request['body'];
                    break;
                case 'multipart/form-data':
                    $options['multipart'] = array_map(function ($key, $value) {
                        return ['name' => $key, 'contents' => $value];
                    }, array_keys($request['body']), $request['body']);
                    break;
                default:
                    $options['body'] = $request['body'];
            }
        }

        return $options;

How can I enable the coupon input box on the customer order pay page?

When a customer clicks on the link to go to their payment page, the ‘Have a Coupon?’ input box does not appear. I haven’t made any adjustments to the templates.

Do you have any ideas on how I can make the coupon input box visible on the customer payment page?

The location I am referring to is:

/checkout/order-pay/<order_id>/?pay_for_order=true&key=<order_key>
Screenshot : https://prnt.sc/-T4dnbDTuPTW

Black Screen Modal Appears in Table Actions on Laravel Filament v3 Resource

I am using Laravel Filament v3 and encountered an issue when generating a resource. I generated the resource using the following command:
php artisan make:filament-resource Anggota --generate

The resource generation completed successfully, but I am experiencing strange behavior in the table view of the generated resource. Specifically:

  • When I perform a search, apply a filter, change the number of items displayed, or navigate to another page in the table, a black screen modal immediately appears.
  • To view the updated data (e.g., navigating to page 2), I have to manually reload the page. After reloading, the table correctly shows the intended data (e.g., page 2).

I didn’t modify anything from the default generated resource
Environment Details:

Here is what I have tried so far:

  • Ensuring that JavaScript and CSS assets are up to date.
  • Clearing cache using php artisan cache:clear and php artisan view:clear.
  • Rechecking the generated code, but I didn’t modify anything from the default generated resource.

Uncaught (in promise) TypeError: – website loads the data but error message in console

i am trying to build a simple website, fetching data from github.
I have two datasets here.
The currentAPI is loaded correctly, while the other one throws error message “Uncaught (in promise) TypeError: album is not defined”, nevertheless the website loads the data!

    I have an async function:
    
            async function getData() {
            
            
              const previousPromise=fetch('https://raw.githubusercontent.com/balintov/matchmaker/refs/heads/main/previousPicturesAPI');
              const currentPromise=fetch('https://raw.githubusercontent.com/balintov/matchmaker/refs/heads/main/currentPicturesAPI');
              const responses = await Promise.all([previousPromise, currentPromise]);
              const dataPromises = responses.map(r => r.json());
              const [previous, current] = await Promise.all(dataPromises);
          for (var props in previous) {
            document.getElementById('main').innerHTML+= `<div class="previousTitle"><h2> Korábbi részek </h2><p>${previous[props].series} évad</p></div>`
            for (var episodes in previous[props]) {
              for (var episode in previous[props][episodes]) {
        
                //THIS CONSOLE MESSAGE RETRIVES THE DATA
                console.log(previous[props][episodes][episode].album.photolink);
        
                var episodeProp= previous[props][episodes][episode];
                document.getElementById('main').innerHTML+= `<div class="episode-container">
                <div class="episode-head">

/* HERE THE DATA WORKS, DOES NOT THROW MESSAGE */
                <h2>${episodeProp.episode_date}</h2>
                <p><a href=${episodeProp.episode} target="_blank">Hallgatom az epizódot!</a></p>
                </div>
                <div class="match-container">
                <div class="album-container">
                <div class="content-container">
                <h3>Album</h3>
    /* FROM HERE THROWS THE ERROR MESSAGE */
                <img src="${episodeProp.album.photolink}" alt="${episodeProp.album.description}" width="350" height="450" class="image">
                <p>${episodeProp.album.song}</p><p><a href="${episodeProp.album.spotifylink}" target="_blank">Hallgatom ▶️</a></p>
                </div>
                </div>
                <div class="picture-container">
                <div class="content-container">
                <h3>Kép</h3>
                <img src="${episodeProp.picture.photolink}" alt="${episodeProp.picture.description}" width="350" height="450" class="image">
                <p>${episodeProp.picture.description}</p>
                </div>
                </div>
                </div>
                </div>`
              }
            }
          }
        
        
        }
        
        getData();

I put the data set in JSON validator, I put the JS file into JS validator.
As I mentioned in the code comment, before the template literal string the data is not undefined.
Also in the template literal some data work perfectly.

The exact error message is: “Uncaught (in promise) TypeError: episodeProp.album is undefined”

I really do not understand what the problem is, could someone give a clue?

IN Google Apps Script How to get current active/triggered trigger ID ,

I have build an Sheets Add-on Which performs a task based on trigger setup by user
So the problem is that User sets triggers for multiple sheets e.g Sync

the trigger is executed but only for 1st trigger in the list of triggers not all

The PROBLEM IS only one trigger is being triggered for all of the setup triggers

Logs for one trigger & the same logs comes for all triggers

Active Trigger: -5962537404932988746 for function: fetchSynctriggerWithDetails
Active Trigger: -9139074510508922527 for function: fetchSynctriggerWithDetails
Active Trigger: -1495623190131824397 for function: fetchSynctriggerWithDetails
Active Trigger: -1224866675796805716 for function: fetchSynctriggerWithDetails
Active Trigger: 1983234386806141271 for function: fetchSynctriggerWithDetails
Active Trigger: -8082155554848723508 for function: fetchSynctriggerWithDetails

Response: {"success":true,"triggerDetails":{"trigger_id":"-5962537404932988746","sheet_name":"SKU","databaseid":"1","trigger_time":"1hour"}}

so the problem is it has all the triggers but it always run for

Response: {“success”:true,”triggerDetails”:{“trigger_id”:”-5962537404932988746″,”sheet_name”:”SKU”,”databaseid”:”1″,”trigger_time”:”1hour”}}

Because it can;t find
var triggerId = currentTrigger.getUniqueId();
for each trigger
& each time it returns -5962537404932988746 as current trigger ID

which is wrong

ANY HELP IS APPRECIATED


function createSyncTrigger() {

/// all the setup for setting up trigger 

// I am also saving trigger in PropertiesService

PropertiesService.getScriptProperties().setProperty(triggerId, JSON.stringify(triggerDetails));

}


Code snippet to fetch trigger details


function getTriggerDetailsSync() {
  var triggers = ScriptApp.getProjectTriggers();
   // Log all active triggers for debugging
  triggers.forEach(trigger => {
    Logger.log('Active Trigger: ' + trigger.getUniqueId() + ' for function: ' + trigger.getHandlerFunction());
  });

   //var currentTrigger = triggers.find(trigger => trigger.getHandlerFunction() === 'fetchSynctriggerWithDetails');

 // Get the current trigger that invoked this function
  var currentTrigger = ScriptApp.getProjectTriggers().find(trigger => 
    trigger.getHandlerFunction() === 'fetchSynctriggerWithDetails'
  );

  if (!currentTrigger) {
    Logger.log('No trigger found for fetchSynctriggerWithDetails');
    return null;
  }

  var triggerId = currentTrigger.getUniqueId();

}

Angular 17: localStorage is not defined Error After Saving Changes and Browser Stuck in Reloading State

When i run project in angular 17 it runs successfully. However when i made some changes in code and save changes then:

The browser page stucks in a reloading state

Also this error shown up:

Error during ngOnInit: ReferenceError: localStorage is not defined

Here is my ngOnInit code block:

async ngOnInit() {
    try {
      await this.fetchUsers();
  
      this.chatService.fetchMessages();
      this.chatService.messages.subscribe((messages) => {
        this.messages = messages;
      });
  
      const users = this.authService.getUsers();
      const { username, id } = this.authService.getUserNameFromToken() || {};
      this.name = username ?? '';
      console.log("Display token name:", this.name);
      let token = localStorage.getItem('authToken');
      console.log("Token: ",token);
      this.id = id ?? '';
    } catch (error) {
      console.error("Error during ngOnInit:", error);
    }

  }
```[![Here is image of browser page which stucks in loading state when i made changes in code and save them][1]][1]


  [1]: https://i.sstatic.net/4jvdngLj.png

FormData Not Appending Files in React

I’m working on a React component that allows users to upload files. The files are managed in a state array where each file has additional metadata such as a unique id (required for DataGrid) and a docType field (e.g., INVOICE).

Here’s the state definition:

export interface EnrichedFile {
  id: string; // Unique ID for each file (required for DataGrid)
  docType: string; // A description of the file, e.g., INVOICE
  file: File; // The actual file object
}

const [selectedFiles, setSelectedFiles] = useState<EnrichedFile[]>([]);

Component Code:

Below is the relevant portion of my component where users can drag-and-drop or browse files to upload:

return (
  <Box component="div" className="w-96 overflow-hidden">
     .....
  </Box>
    {selectedFiles.length !== 0 && (
      <Animated className="w-full mt-4 h-48" animationIn="fadeInUp" animationOut="fadeOut" isVisible={true}>
        <ExDataGrid
          processRowUpdate={updateRowHandler}
          disableColumnMenu
          disableColumnFilter
          disableDensitySelector
          columnHeaderHeight={36}
          slots={{
            footer: () => (
              <div className="flex justify-center">
                <LoadingButton onClick={uploadHandler} variant="contained" color="primary" loading={isPending}>
                  Upload
                </LoadingButton>
              </div>
            ),
          }}
          columns={columnsDocumentsUpload(deleteFileUpload)}
          rows={selectedFiles}
        />
      </Animated>
    )}
  </Box>
);

Upload Process:

When I click the Upload button, I create a FormData object and attempt to append the files and metadata before sending it to the server via Axios. However, the FormData appears to be empty when inspected.

Here is my uploadHandler function:

const uploadHandler = useCallback(async () => {
  // Validate that all files have a docType
  const hasError = selectedFiles.some(file => file.docType.trim() === '');
  if (hasError) {
    return toast.error('Please select a document type for all files');
  }

  // Create FormData object
  const formData = new FormData();
  selectedFiles.forEach(file => {
    if (file.file instanceof File) {
      formData.append('files', file.file); // Append the actual file
      formData.append('metadata', JSON.stringify({ id: file.id, docType: file.docType })); // Include metadata for each file
    } else {
      console.error("Invalid file object:", file.file);
    }
  });

  // Debugging: Log FormData entries
  for (const [key, value] of formData.entries()) {
    console.log(`${key}:`, value);
  }

  mutate(formData);
}, [selectedFiles, mutate]);

Expected Behavior:

The FormData object should include the appended files (files) and metadata (id, docType) and send them to the server.

Questions:

  1. Why is the FormData object empty even though selectedFiles contains valid File objects?
  2. Am I appending files to FormData incorrectly?

Node.js v22.12 Ends Immediately Without Any Output When Running a File on Windows

I recently upgraded Node.js on my Windows machine to version v22.12, and now any script I run from a file exits immediately without displaying any output. For example:

> node test.js
# (no output, program finishes instantly)

Here is a minimal example of test.js (though the content seems irrelevant; even a single console.log() fails to produce output):

console.log("Hello from Node.js");
setInterval(() => {
  console.log("Still running...");
}, 2000);

Key observations:

  1. If I run the same code inline using -e, it does work:
    node -e "console.log('Hello from inline'); setInterval(() => {console.log('Still running inline...');}, 3000)"
    
  2. If I downgrade Node.js to v20.18, the file-based execution works as expected, producing output as normal.
  3. Before upgrading to 22.12, everything worked correctly on the same machine.
  4. After reverting to 20.18, it started working again without changing any other settings.

Question:

  • Was there a change in Node.js v22.12 that affects how scripts should be started on Windows?
  • Or could there be a specific configuration or security policy on my Windows PC that might cause this behavior?
  • Has anyone else encountered this issue or found a workaround?

For now, I’m okay staying on v20.18 since it resolves the problem, but I’d prefer to upgrade if there’s a known fix or setting adjustment. Any insights would be much appreciated!

How can I add a console.log statement to a JavaScript file on a live website?

I want to see print something in console so I can see the values, its a live website that I dont have control, its not mine.

Here is what I did.

  1. Went to SOURCES tab
  2. opened that Javascript file
  3. put console.log()
  4. clicked CTRL+S
  5. Then without re-freshing website, I clicked on that particular
    button on website, AJAX was sent, but no message in console

NOTE: that orange icone you see? it says “changes to this file were not saved to file system”

PS: I know I can see in XHR request payload but thats not I want, that is different data, I want see data at that specific point.

enter image description here

Java OpenCv to Maven

Is there any way to get OpenCV from repository? Which artifact should I add to pom.xml? Every tutorial I’d found is from ’14 and it seems like something changed – they say it is’nt in official Maven repository yet, but I’ve found entry:

when I’m using System.loadLibrary(Core.NATIVE_LIBRARY_NAME). Can I add this library in a way that would make my project include it and ‘forget’ about manually adding it to classpath?

How to prevent downloading the desktop component code in Next.js when using dynamic imports based on user-agent?

I’m trying to create a layout in Next.js where the component rendered depends on the device (mobile or desktop). I want to prevent the desktop layout’s source code from being downloaded to the browser if the user is on a mobile device. Here’s what I have:



"use server";

import React, {ReactNode, ComponentType} from "react";

import {parseUserAgent} from "@repo/helpers";
import dynamic from "next/dynamic";
import {headers} from "next/headers";

interface Props {
  CommonWrapper?: ComponentType<{children: ReactNode}>;
  MobileComponent: () => Promise<{default: React.ComponentType<any>}>;
  DesktopComponent: () => Promise<{default: React.ComponentType<any>}>;
}

const withResponsiveLayout = async ({
  CommonWrapper,
  MobileComponent,
  DesktopComponent,
}: Props) => {
  const header = new Headers(headers());
  const parsedUserAgent = parseUserAgent(header);
  let isMobile = parsedUserAgent?.device.is("mobile");

  const Wrapper = CommonWrapper ?? React.Fragment;
  const Component = isMobile
    ? dynamic(MobileComponent)
    : dynamic(DesktopComponent);

  return (
    <Wrapper>
      <Component />
    </Wrapper>
  );
};

export default withResponsiveLayout;



// example

'use server'

async function Page() {
  const data = await getSomeData();

  return await withResponsiveLayout({
    CommonWrapper: ({children}: PropsWithChildren) => (
      <MandatoryAuthWrapper>
        <CommonProvier initialData={data}>{children}</CommonProvier>
      </MandatoryAuthWrapper>
    ),
    DesktopComponent: () => import("./Main"),
    MobileComponent: () => import("./MobMain"),
  });
}


I’m trying to render either a mobile or desktop layout based on the user-agent, and I want to ensure that the desktop layout never gets downloaded by the browser if the user is on a mobile device. I don’t want to make the layout responsive but rather load an entirely different layout based on the device.

Am I doing something wrong in my approach? How can I ensure the desktop component is excluded from the client-side bundle entirely when the user is on a mobile device?

Need to print a receipt using network printer in a react Web application

I made a restaurant web application. I need to print the billing receipt in react web application using a network printer but when installing necessary libraries /packages it’s not getting installed and the same error is repeating on different libraries. Need to fix this code in front-end. When I print the code the receipt design is getting printed instead the HTML code is getting printed with the tags. And I’m designing it using tailwind css. The code is connected through IP address of the printer but when the print receipt button is clicked it prints the same HTML raw code which is given as text and not printing the receipt design.

I tried packages like node-thermal-printer, npm point-of-sale, npm escpos-network but none of them are installing and showing error as Unsupported engine node version. I tried changing the node versions but still it’s not getting installed. When the print receipt button is clicked it should not show the pop-up page which shows to select the printer type, print color, and etc., instead it should print the receipt directly. This should be done in webpage application.

Implementing Deep Linking for Website-to-App Redirection in React Native

When a user visits certain pages on a website, and they have the app installed, I’d like the app to open instead. I’m not entirely sure how to achieve this, but I assume it involves adding a meta tag or similar functionality to the pages.

For example, if the hosted website is https://example.com/ and a user visits https://example.com/stream, I’d like the XYZ application to open (if installed) and load the stream page within the app.

This functionality needs to be implemented in React Native. While I’m familiar with handling deep linking, this approach seems to require a different method.