Node.js fetch to BoardGameGeek API always returns 403 Forbidden despite using API token [closed]

I’m trying to fetch board game information from the BoardGameGeek XML API using Node.js. I have a valid API token, but every request returns a 403 Forbidden response.

Here’s my current setup:

async function getInfoFromBGG(gameId) {

  const url = `https://rpggeek.com/xmlapi2/thing?id=${gameId}`

  let result
  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), 5000)

  try {
    const response = await fetch(url, {
      headers: {
        "Authorization": "Bearer i put my token here",
        "User-Agent": "BoardgameAlbum/1.0 ([email protected])",
        "Accept": "application/xml"
      }
    });

    clearTimeout(timeoutId)

    if (!response.ok) {
      console.log(response)
      console.log(`HTTP Error: ${response.status} ${response.statusText}`)
      return { error: "Failed to fetch from BGG" }
    }

    const xml = await response.text()
    const parser = new DOMParser()
    result = parser.parseFromString(xml, "text/xml")

    const item = result.querySelector("item")
    if (!item) {
      return { error: "Game not found" }
    }

    return {
      id: item.getAttribute("id"),
      name: item.querySelector("name[type='primary']")?.getAttribute("value"),
      yearPublished: item.querySelector("yearpublished")?.getAttribute("value"),
    }

  } catch (error) {
    clearTimeout(timeoutId)
    console.error("Fetch error:", error)
    if (error.name === "AbortError") {
      return { error: "Request timed out" }
    }
    return { error: "Internal server error: " + error.message }
  }
}

the same code will work without any problem in browser, but i have to remove the token if i want the code to be executed perfectly. i have tried different approaches but noting helped. the code wont run in server.

I’m trying to fetch game data from the BoardGameGeek API. I’ve tried several approaches, both from the frontend and Node.js backend:

Using fetch from the frontend with Authorization: Bearer and User-Agent headers.

Adding Accept: application/xml and other headers recommended by BGG.

Using node-fetch in Node.js with the same headers.

Using the bgg-xml-api-client package in Node.js.

Verified that the API token is valid and not expired.

Despite this, I always get either:

CORS errors when calling from the frontend, or

403 Forbidden when calling from Node.js, even with correct headers.

I expected to be able to fetch game data from BGG API from my server without these errors.

Has anyone successfully fetched data from BGG API recently? Are there special requirements for browser requests or server requests with their token?

JS Slow http request [closed]

i have a website that is selling some products online, and everyday there are updates, i try to be the first that is getting those products, and i created a bot in js runned by tampermonkey to make this automation and get all first, it worked well till a moment, site started to run slow for me ( and maybe for all rest users also) and when i was trying to buy the products when the update was launched, other users(or maybe one specific user) is buying all what i need before me, i tried to change the script , so that it will not click the ui elements, but trough http requests and stuff, still the server response are way too slow to get in front and buy all the things, is there any solution to make this happen and be the first ? thank you for the attention

i tried ui auto clicker script, and http requests

Arabic text gets corrupted to “E1-(‘ (‘D9’DE” when creating PDF annotations with @iwater/annotpdf library

I’m using the @iwater/annotpdf library to create PDF annotations in an Angular application. When I try to create free text annotations with Arabic text, the text gets corrupted to unreadable characters.

Expected Result:
Arabic text should display as: مرحبا بالعالم (Hello World in Arabic)

Actual Result:
Arabic text displays as: E1-(‘ (‘D9’DE

// In my free-text-annotation.service.ts
 createFreeTextAnnotation(annotation: any): any {
  return this.annotationFactoryService.annotationFactory!.createFreeTextAnnotation({
  page: pageNumber - 1,
  rect: annotation.rect,
  contents: "مرحبا بالعالم", // Arabic text
  author: annotation.author || 'User',
  color: annotation.color || '#FF0000',
  fontSize: annotation.fontSize || 12
  });
}

What I’ve tried:

  1. Setting textAlign: ‘right’ and direction: ‘rtl’ for RTL support
  2. Using UTF-8 encoding/decoding
  3. Adding Arabic font families like “Noto Sans Arabic”
  4. Base64 encoding the text before passing to the library

Environment:

  • Angular 17

  • @iwater/annotpdf library

  • English text works fine, only Arabic text gets corrupted

Question:

How can I properly handle Arabic text in PDF annotations using the @iwater/annotpdf library? Is there a specific encoding or configuration needed for Unicode/Arabic characters?

React image drag function not working – function not detecting the mousedown on image

I am trying to build an image zoom / drag application but it is not working. I have a ‘mousedown’ event handler attached to the image I want to drag but it is not being detected. The mousedown is detected when I attached the document to the event handler but not the image, I’m struggling to understand why.

  document?.removeEventListener("mousedown", handleMouseDown);

If anyone has any suggestions I would be interested to hear them…
Thank you.

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import { useState, useEffect } from "react";
import { useRef } from "react";
import img1 from "./img1.jpg";
import img2 from "./img2.jpg";


function App() {
  const images = {
    1: img1,
    2: img2
  };

  return (
    <div>
      <ImageZoomInOut img1={img1} images={images} />
    </div>
  );
}
////////////////////////////////////////////

function ImageZoomInOut({ images }) {
  //state for img scale
  const [scale, setScale] = useState(1);
  //state for img position
  const [position, setPosition] = useState({ x: 0, y: 0 });

  //reference to the img element
  const imageRef = useRef(null);

  //zoom in function
  function handleZoomIn() {
    return setScale((scale) => scale + 0.05);
  }
  //zoom out function
  function handleZoomOut() {
    return setScale((scale) => scale - 0.05);
  }

  //image drag and zoom/////////////////////////////

  useEffect(() => {
    const image = imageRef.current;
    let isDragging = false;
    let prevPosition = { x: 0, y: 0 };

    //mouse down event handler for starting img drag

    const handleMouseDown = (e) => {
      isDragging = true;
      prevPosition = { x: e.ClientX, y: e.clientY };
    };

    //mouse move event handler for dragging img

    const handleMouseMove = (e) => {
      if (!isDragging) return;

      const deltaX = e.clientX - prevPosition.x;
      const deltaY = e.clientY - prevPosition.y;
      prevPosition = { x: e.clientX, y: e.clientY };
      setPosition((position) => ({
        x: position.x + deltaX,
        y: position.y + deltaY,
      }));
    };

    //mouse up event handler for ending img drag

    const handleMouseUp = () => {
      isDragging = false;
    };

    const image1 = document.getElementById("2");

    //add event listeners
    image1.addEventListener("mousedown", handleMouseDown);
    image1.addEventListener("mousemove", handleMouseMove);
    image1.addEventListener("mouseup", handleMouseUp);

    //remove event listners on component unmount
    return () => {
      image?.removeEventListener("mousedown", handleMouseDown);
      image?.removeEventListener("mousemove", handleMouseMove);
      image?.removeEventListener("mouseup", handleMouseUp);
    };
  }, [imageRef, scale]);

  //////////
  return (
    <div style={{ position: "relative", overflow: "hidden" }}>
      <div className="btns">
        <button className="btn1" onClick={handleZoomIn}>
          +
        </button>
        <button className="btn2" onClick={handleZoomOut}>
          -
        </button>
      </div>
      {/* image element */}
      <img
        ref={imageRef}
        id="2"
        src={images[2]}
        alt=""
        style={{
          width: "900px",
          height: "auto",
          cursor: "move",
          transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
        }}
        draggable={false}
        onClick={() => console.log("hi")}
      />
    </div>
  );
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

How to keep the React DateRange calendar from react-date-range focused on the end month after selecting the final date?

I’m using the DateRange component from the react-date-range library.
When I select a start date and then an end date, the calendar automatically jumps back to show the month of the start date, even if the end date is in a different month.

I would like the calendar to stay focused on the month of the end date after selection — for example, if I select October 28 as the start and December 3 as the end, I want the calendar to remain showing December, not go back to October.

Here’s a simplified version of my current code:

<DateRange
      locale={customPtBR}
      editableDateInputs={true}
      onChange={(item) => {
        setState([item.selection]);
      }}
      preventSnapRefocus="disabled"
      moveRangeOnFirstSelection={false}
      months={1}
      ranges={state}
      className="border-radius"
      minDate={new Date()}
    />

I noticed there’s a prop called onRangeFocusChange, I tried using it but the behavior doesn’t change. I also used preventSnapRefocus=”disabled” and nothing changes too.

How can I make the DateRange component stay on the end date’s month after I select the final date, instead of automatically going back to the start date’s month?

Having An Issue to know if user has paid the amount for product on order summary and payment page in ecommerce [closed]

currently i am making this website using react js + tailwind + node js + express js + mysql workbench

i am currently creating ecommerce and everything is set in whole website from adding product to cart and login and proceed the user the payment page and also we have given the option to user to enter its email and select address which user added from its user dashboard or profile seciton and also is able to pay qr code using any upi platform

and before payment the product data which user wants to order and all address and email all information is being stored in Database for tempory as order_status = pending but i want that how can make sure user has paid and once user has done payment then we will make order_status of that purticular product change to “confirmed”

this is my current recent_order databse table in which the product details would be stored

Table: recent_order
Columns:
id int AI PK
order_id varchar(100)
payment_method enum(‘COD’,’CARD’,’UPI’,’NET_BANKING’,’PAYPAL’)
payment_id varchar(150)
name varchar(150)
phone_number varchar(20)
email_id varchar(150)
address_id int
total_amount decimal(10,2)
order_status enum(‘PENDING’,’CONFIRMED’,’SHIPPED’,’DELIVERED’,’CANCELLED’,’RETURNED’)
order_placed_date datetime
order_arrived_date datetime
product_id json
created_at timestamp
updated_at timestamp
deleted_at tinyint(1)

now how can archive that without using any payment gateway ?

i am expecting that once payment is done by the user then it would check in databse if payment is done in every five seconds using setTimeout and once payment is done then it would update order_status and clear the interval of every five second check

Perl Multilanguage PDF generation [closed]

In perl any module available for multilanguage pdf generation ? if yes then please guide me for this ?

please give me some tips to how to generate multilanguage pdf genaration.
and guide me for this how to create modal in perl

i am trying but any single language show in pdf other language is hide and show box in this palce

How can I calculate the number of years between a date and today [closed]

there is a lot of questions about this situation but the best i’ve found is these 2 similar questions.

I’ve been using jQuery for a short time and I didn’t find the way to achieve what i need from my side even with these example:

1.
Calculate the number years between a historic date and today

2.
How can I calculate the number of years between two dates?

I want a div where i can display automatically each year the number of years between a specific date and today. I think jquery could be the simpliest way to achieve that ?

At this time i’m working on this part of code i’ve found who displayed the actual date in a div automatically, i don’t know how to edit it.

here is a snippet:

$(document).ready(function() {
  $(".wl-creation-date").append(new Date().getFullYear());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<span class='wl-creation-date'>+</span>

Here is my jsfiddle: https://jsfiddle.net/kodjoe/nLm8r6dy/4/

How can I invoke aplay from nginx/php

I am trying to make aplay play a wav file on my Beaglebone running Debian (trixie).

I can do it from an ordinary login user no problem.

aplay -D dmix:CARD=Device,DEV=0 somefile.wav

works perfectly and plays the sound on a USB speaker, so I believe the hardware is all just fine. The problem arises when I try and invoke aplay from a PHP script running under nginx. That is running under user www-data so I added www-data to the audio group. Then I was able to do this:

sudo -u www-data aplay -l

which shows me the active audio devices and I can also tell it to play the audio file, and it does successfully. It only fails when it is running in the real environment ie under nginx. In that environment aplay returns a status 1 and I can’t tell why.

More specifically, PHP runs a shell_exec to invoke a small bash script that invokes aplay and logs a few things. I can run this bash script from my login user and it works, and under nginx/php it logs its output just fine so I know it is running and that it is invoking the wav file I want it to.

The target file name is definitely correct. I use the full path and I log it. I can copy/paste from the log and invoke aplay with that file and it works fine. Permissions on the file are -rw-rw-r-- so it is readable by anyone. It is owned by a different user, though.

User www-data has no ~/.asoundrc file and neither does my login user.

I know this can work because I had it running on this machine up until I rebuilt it. I’m fairly sure there is some, hopefully obvious, trick I have forgotten from the first time I set it up, though that was pre-trixie.

Doctrine referenceone gives only superclass

I’m refactoring old symfony 3 and doctrine 1.3 project;

I have 2 classes in same table: Journal and Conference mapped by their same parent Periodic.

/**
 * @ODMDocument(collection="periodics")
 * @ODMInheritanceType("SINGLE_COLLECTION")
 * @ODMDiscriminatorField("periodic_type")
 * @ODMDiscriminatorMap({
        "journal"=BundleDocumentJournal::class,
        "conference"=BundleDocumentConference::class,
    })
 * @GedmoSoftDeleteable(fieldName="deletedAt", timeAware=false)
 */
class Periodic {
...
}

/**
 * @ODMDocument()
 */
class Conference extends Periodic {
...
}

/**
 * @ODMDocument()
 */
class Journal extends Periodic {
...
}

I have also a class Assembly with referenceOne to Periodic:

class Assembly{
    /**
     * @ODMReferenceOne(
     *     targetDocument=Periodic::class,
     *     nullable=true
     * )
     */
    protected $periodic;

    /**
     * @return mixed
     */
    public function getPeriodic()
    {
        return $this->periodic;
    }

    /**
     * @param mixed $periodic
     * @return $this
     */
    public function setPeriodic($periodic)
    {
        $this->periodic = $periodic;
        return $this;
    }
}

The is a problem with getting Periodic from Assembly as I got object of Periodic class not Journal or Conference.
Please advice how to deal with it.

Laravel stancl/tenancy: Tenant migrations not running (separate tenant DBs, migrations in database/migrations/tenant)

I am running tenant new migrations (orders/order_items) that live in database/migrations/tenant across multiple tenants. Each tenant has its own database (tenant_1, tenant_2, tenant_3, …) and there are some tables already. The central/system database is separate.

What happens when i run migrations using
php artisan tenants:migrate --force, tenant_1 migrates successfully.For tenant_2, tenant_3, etc., the command says “Nothing to migrate.
The new tables (orders, order_items) are not created in those tenant DBs. And new migrations are on migration/tenant folder

i have tried to checked config/tenancy.php includes the tenant migration path:

'migration_parameters' => [
        '--force' => true, // This needs to be true to run migrations in production.
        '--path' => [database_path('migrations/tenant')],
        '--realpath' => true,
    ],

when i run php artisan tenants:list it show perfectly real total of tenants

I am using laravel 12 and stancl/tenancy: ^3.8

how to simulate transactional behavior (rollback) for file system operations in php

Since PHP’s file system functions like rename(), copy() & … are not transactional, there’s no built-in rollback mechanism. I’m working on a PHP project where I need to perform multiple file system operations in sequence. The challenge is that if one operation fails, I want to rollback the previous ones to maintain consistency, similar to how database transactions work (especially when there are more than two operations involved, managing consistency becomes even more challenging. If one step fails, I need a way to undo all previous changes to avoid leaving the system in a partial or broken state). I’m looking for a reliable strategy to simulate transactional behavior for such operations.

Note : For simplicity, input validation, path sanitization, and security checks & … are omitted in this example.

<?php

$oldname = $_SESSION['oldname'];
$newname = $_POST['newname'];

$oldFile = './' . $oldname . '/' . $oldname . '.php';
$newFile = './' . $oldname . '/' . $newname . '.php';

$oldDir = './' . $oldname;
$newDir = './' . $newname;

if (file_exists($oldFile) && rename($oldFile, $newFile)) {
    if (file_exists($oldDir) && rename($oldDir, $newDir)) {
        //if (...) {

        try {
            $conn->beginTransaction();

            $update1 = $conn->prepare("UPDATE table1 SET name=? WHERE name=?");
            $update1->execute([$newname, $oldname]);

            $update2 = $conn->prepare("UPDATE table2 SET name=? WHERE name=?");
            $update2->execute([$newname, $oldname]);

            //...

            if ($update1->rowCount() > 0 && $update2->rowCount() > 0) {/* if ($update1->rowCount() > 0 && $update2->rowCount() > 0 && ...) { */

                $conn->commit();
                echo 'changed !';
            } else {

                $conn->rollBack();
                echo 'didnt change !';
            }
        } catch (PDOException $e) {

            $conn->rollBack();
            echo 'didnt change !';
        }
        //}
    } else {
        echo 'didnt change !';
    }
} else {
    echo 'didnt change !';
}
async function changename() {
    const newname = encodeURIComponent(document.getElementById('username').value);
    const formData = 'newname=' + newname;
    try {
        const response = await fetch('../script.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: formData
        });
        if (!response.ok) {
            throw new Error();
        }
        const responseText = await response.text();
        //...
    } catch (error) {
        msg('unfortunately, something went wrong !');
    }
}
document.getElementById("changename").addEventListener("click", changename);

Thanks in advance for any insights or suggestions !

Panther can’t connect to a port with fsockopen

I have a need for end to end testing, when i launch a test that imply to open a page, the same problem come back each time : fsockopen(): Unable to connect to 127.0.0.1:9080 (No connection could be made because the target computer actively refused it)
Or another same port.

I use wamp, and vhost, where i have a symphony app. I’ve tried to change navigator – chrome – and firefox, i have checked the versions if they were compatible, i’ve also made sure it wasn’t the chromedriver or geckodriver that had problems. And of course reinstalled multiple times.

Also, not just fsockopen, the terminal shows : Error output: ‘.’

I’m open to any idea, i’m really stuck.

enter image description here

-> Reinstalled
-> Change browser as chrome with panther is known to have several problems
-> Checked and made sure every version where compatible (chrome, with the chromedriver, firefox with geckodriver)

How can I calculate the number of years between a date and today in jquery

*Update my question, since i can’t use microsoft datediff-function:

there is a lot of questions about this situation but the best i’ve found is these 2 similar questions. But i didn’t find the way to achieve what i need:

1.
Calculate the number years between a historic date and today

2.
How can I calculate the number of years between two dates?

I want to create a jquery function who gives me the number between a date and today in my div ? Because at this time i can only show the actual date in my div.

here is a snippet:

$(document).ready(function() {
  $(".wl-creation-date").append(new Date().getFullYear());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<span class='wl-creation-date'>+</span>

Here is my jsfiddle: https://jsfiddle.net/kodjoe/nLm8r6dy/4/

Hardhat3: How to deploy smartcontract in script on localhost?

I’m playing with a simple project of issuing ERC20 token. Following the example in hardhat3 doc, I successifully deployed the contract on localhost with CLI as below:

  • run local blockchain npx hardhat node
  • deploy the smart contract npx hardhat ignition deploy --network localhost ignition/modules/LeoCoin.js

then interact with the smart contract in file under scripts also fine.

But got trouble when trying deploy that contract in script on loaclhost

  1. Code for ../Ignition/modules/LeoCoin.js
import { buildModule } from '@nomicfoundation/hardhat-ignition/modules';

export default buildModule('LeoCoin', (m) => {
  const LeoCoin = m.contract('LeoCoin', ['LeoCoin', 'LC', 100000]);

  return { LeoCoin };
});
  1. Code for the script I want to run
import LeoCoinModule from '../ignition/modules/LeoCoin.js';
import hre from 'hardhat';

async function main() {
  const connection = await hre.network.connect();
  const { LeoCoin } = await connection.ignition.deploy(LeoCoinModule);
  let res = await LeoCoin.getAddress();
  console.log(`LeoCoin deployed to: ${res}`);
  const accounts = await connection.ethers.getSigners();
  res = await LeoCoin.balanceOf(accounts[0].address);
  console.log(res);
}

main().catch(console.error);

And I run it with npx hardhat run scripts/script.js --network localhost

I received below result:

LeoCoin deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3
Error: could not decode result data (value="0x", info={ "method": "balanceOf", "signature": "balanceOf(address)" }, code=BAD_DATA, version=6.15.0)
    at makeError (E:CodeOptionnode_modulesetherssrc.tsutilserrors.ts:698:21)
    at assert (E:CodeOptionnode_modulesetherssrc.tsutilserrors.ts:719:25)
    at Interface.decodeFunctionResult (E:CodeOptionnode_modulesetherssrc.tsabiinterface.ts:916:9)
    at staticCallResult (E:CodeOptionnode_modulesetherssrc.tscontractcontract.ts:346:35)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async staticCall (E:CodeOptionnode_modulesetherssrc.tscontractcontract.ts:303:24)
    at async Proxy.balanceOf (E:CodeOptionnode_modulesetherssrc.tscontractcontract.ts:351:41)
    at async main (file:///E:/Code/Option/scripts/Option.js:16:9) {
  code: 'BAD_DATA',
  value: '0x',
  info: { method: 'balanceOf', signature: 'balanceOf(address)' },
  shortMessage: 'could not decode result data'
}

And I don’t see the node terminal return any message regarding deployment.

Does it mean the contract is not deployed on localhost? if yes, how to?