Javascript backend Output: Unexpected end of JSON input

I am new to fullstack development and I’m trying to send data from my frontend javascript to my backend. For debugging I tried to send the data back to the frontend, but I get the error “{success: false, error: ‘Unexpected end of JSON input’}”.

Here is my frontend code:

form.addEventListener("submit", async (e) => {
      e.preventDefault();

      const team_name = document.getElementById("team_name").value;
      const post_description = document.getElementById("post-description").value;
      const posts = postList;

      const fullData = {
        team_name,
        post_description,
        posts,
        email: user_email
      };
      console.log("Data sent to backend:", fullData);

      const res = await fetch("https://blue-heart-681f.alexandrosmostl.workers.dev/create_team", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(fullData)
      });


      const result = await res.json();
console.log("Backend Response:", result);
console.log("All user data from backend (data):", result.data);

    });

And here is my backend code:

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type"
};

export default {
  async fetch(request, env, ctx) {
    const headers = {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
      "Access-Control-Allow-Headers": "Content-Type",
    };

    if (request.method === "OPTIONS") {
      return new Response(null, { headers: corsHeaders });
    }

    const url = new URL(request.url);
    const pathname = url.pathname;

if (request.method === "POST" && pathname === "/create_team") {
  const headers = {
    "Content-Type": "application/json",
    ...corsHeaders,
  };

  try {
    let body;
    try {
      body = await request.json();
    } catch (e) {
      return new Response(JSON.stringify({ success: false, error: "Invalid JSON-Body" }), { headers });
    }

    const { team_name, email, post_description, posts } = body;

    if (!team_name) {
      return new Response(JSON.stringify({ success: false, error: "Team-Name is missing" }), { headers });
    }
    if (!email) {
      return new Response(JSON.stringify({ success: false, error: "Email is missing" }), { headers });
    }
    if (!post_description) {
      return new Response(JSON.stringify({ success: false, error: "post_description is missing" }), { headers });
    }
    if (!posts) {
      return new Response(JSON.stringify({ success: false, error: "posts is missing" }), { headers });
    }

    const user = await supabaseGetUserByEmail(email);
    if (!user) {
      return new Response(JSON.stringify({ success: false, error: "User not found" }), { headers });
    }

    let currentTeams = {};
    try {
      currentTeams = user.leading_teams ? JSON.parse(user.leading_teams) : {};
    } catch (_) {}

    const baseId = team_name.toLowerCase().replace(/s+/g, "_").replace(/[^w]/g, "");
    let uniqueId = baseId;
    let counter = 1;
    const existingIds = Object.values(currentTeams);
    while (existingIds.includes(uniqueId)) {
      counter++;
      uniqueId = `${baseId}_${counter}`;
    }

    currentTeams[team_name] = uniqueId;

    await supabaseUpdateUser(email, {
      leading_teams: JSON.stringify(currentTeams)
    });

    return new Response(JSON.stringify({ success: true }), {
  headers: {
    "Content-Type": "application/json",
    ...corsHeaders
  }
});


  } catch (e) {
    return new Response(JSON.stringify({ success: false, error: e.message }), { headers });
  }
}


    return new Response(JSON.stringify({ message: "POST only allowed with /signup, /additional or /login" }), { headers });
  }
};

I’m sorry if my code is messy…

When i test my application, I get the following error message:

Data sent to backend: {team_name: 'wdefre', post_description: '•What we don•Your skillsn•Your profilen•What we offerwdew', posts: Array(1), email: '[email protected]'}
dashboard-script.js:88 Backend Response: {success: false, error: 'Unexpected end of JSON input'}
dashboard-script.js:89 All user data from backend (data): undefined

How to convert the pre-ES6 code to ES6 code [closed]

Consider you have a set of code snippets where the code is written in pre-ES6

function InputMask(options) {
  options = extend({
    formatCharacters: null,
    pattern: null,
    isRevealingMask: false,
    placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
    selection: {
      start: 0,
      end: 0
    },
    value: ''
  }, options)
}

What is the best way to convert this code to ES6? TypeScript is preferable and on top of it. Should we have a class-based transformation or would function-based do the work?

export default class InputMask {

  constructor(options: InputMaskOptions) {
    options = extend(
      {
        formatCharacters: null,
        pattern: '',
        isRevealingMask: false,
        placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
        selection: { start: 0, end: 0 },
        value: '',
      },
      options,
    );
    this.placeholderChar = options.placeholderChar;
    this.formatCharacters = mergeFormatCharacters(options.formatCharacters);
  }
}

This is what I thought of doing and somewhat it works but then there are minor issues like options.formatCharacters is having error of:

Argument of type 'FormatCharacters | undefined' is not assignable to parameter of type 'FormatCharacters'.
  Type 'undefined' is not assignable to type 'FormatCharacters'

and then functionality is kind of broken too.

How to convert the preES6 code to ES6 code

Consider you have a set of code snippet where the code is written in pre-es6

function InputMask(options) {
options = extend({
formatCharacters: null,
pattern: null,
isRevealingMask: false,
placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
selection: {start: 0, end: 0},
value: ''
}, options)
}

What is the best way to convert this code to ES6, typescript is preferrable and on top of it. should we have a class based transformation or does function based would do the work.

export default class InputMask {

  constructor(options: InputMaskOptions) {
    options = extend(
      {
        formatCharacters: null,
        pattern: '',
        isRevealingMask: false,
        placeholderChar: DEFAULT_PLACEHOLDER_CHAR,
        selection: { start: 0, end: 0 },
        value: '',
      },
      options,
    );
    this.placeholderChar = options.placeholderChar;
    this.formatCharacters = mergeFormatCharacters(options.formatCharacters);
  }
}

This is what I thought of doing and somewhat it works but then there are minor issues like options.formatCharacters is having error of “Argument of type ‘FormatCharacters | undefined’ is not assignable to parameter of type ‘FormatCharacters’.
Type ‘undefined’ is not assignable to type ‘FormatCharacters'” and then functionality is kind of broken too. I tried on the internet about this issue, but there isn’t much so kindly help.

Install the oldest dependency versions compatible with my package.json version ranges

Consider a typical JavaScript library published on npm, with dependencies. The package declares its dependencies in package.json, where it does not specify exact versions of those dependencies but rather version ranges with which it purports to be compatible.

It seems to me that ideally, one part of such a library’s CI system or pre-release testing process would be to run the test suite using the oldest possible versions of all dependencies that are consistent with those version ranges. After all, if your package.json says you depend on "libfoo": "^1.2.3" and "libbar": ">=0.2.0" but you haven’t actually tested your latest changes with libfoo 1.2.3 or libbar 0.2.0, then how can you know that your version ranges are still correct? You might have written code that depends on a bugfix introduced in libbar 0.2.1, in which case your declared version range would now be a lie.

How can I do this? Is there some simple incantation I can use to make npm (or Yarn) disregard my lockfile and install the oldest possible versions of all my dependencies?

React Flow documentation site is down — any alternative sources for guidance? [closed]

I’m new to React and working on a project that requires using React Flow. However, the official React Flow documentation seems to be down — I’ve been trying to access it since yesterday without success.

I’ve searched for alternative guides or examples on GitHub, blogs, and YouTube, but I haven’t found anything that provides a complete overview or matches the latest version.

Are there any recommended alternative sources or community resources where I can learn how to use React Flow effectively?

odoo18: How to add WYSIWYG on website portal textarea?

In odoo18, i have customized the view of the frontend page /my/account by inheriting the view “portal.portal_my_details” to add a custom field wrapped into an HTML textarea. I have added the class .o_wprofile_editor_form to the in order to use the nativ frontend public Widget “websiteProfileEditor“:

// enterprise/odoo/addons/website_profile/static/src/website_profil.js:
publicWidget.registry.websiteProfileEditor=publicWidget.Widget.extend({
selector:'.o_wprofile_editor_form',
//...
start: async function () {

const textareaEl=this.el.querySelector("textarea.o_wysiwyg_loader");

My custom xml inherited view:

<template id="portal_my_details_zsb"   inherit_id="portal.portal_my_details">
              <xpath expr="//form" position="attributes">
                    <attribute name="enctype">multipart/form-data</attribute>
                </xpath>
    <xpath expr="//form" position="attributes">
               <attribute name="class">o_wprofile_editor_form</attribute>
    </xpath>
    <xpath expr="//form/div[hasclass('o_portal_details')]/div/div" position="inside">
               
    <div t-attf-class="col-12 py-2 #{error.get('website_description') and 'o_has_error' or ''} col-xl-12">
    <label class="col-form-label form-label" for="website_description">Activités</label>
    <textarea name="website_description" id="website_description"><t t-out="partner.website_description"/>
    </textarea>
                    </div>
        </xpath>
    </template>

After the corresponding page is loaded, the textarea is covered by a spin-icon (loading…). See image

The corresponding rendered html is:

<div class="form-group  col-xl-12"><label class="col-form-label" for="website_description" data-oe-model="ir.ui.view" data-oe-id="10438" data-oe-field="arch" data-oe-xpath="/data/xpath[2]/fieldset/div[8]/label[1]">Activités</label>

<div class="position-relative o_wysiwyg_textarea_wrapper">

<textarea 
class="form-control o_wysiwyg_loader"
name="website_description" id="website_description">
&lt;ul&gt;&lt;li&gt;Coach bien-etre &lt;/li&gt;&lt;li&gt; reiki III &lt;br&gt;&lt;/li&gt;&lt;li&gt;constellateur niv 2&lt;br&gt;&lt;/li&gt;&lt;li&gt;prof Lou Yong&lt;/li&gt;&lt;/ul&gt; 
</textarea>

<div class="o_wysiwyg_loading">
<i class="text-600 text-center fa fa-circle-o-notch fa-spin fa-2x"></i></div></div>
</div>

enter image description here

Why are export conflicts silently removed in ES6 modules

Let’s suppose we have 3 files

// a.mjs
export * from "./b.mjs";
export * from "./c.mjs";

// b.mjs
export const foo = 1;
export const bar = 2;

// c.mjs
export const bar = 3;

Both “b.mjs” and “c.mjs” export bar, so they create a conflict when they’re re-exported from “a.mjs“.

I was expecting either one of the two to “shadow” the other one or the whole thing to throw, but instead it turns out that “a.mjs” only exports foo.

Why is JavaScript pretending that the conflicting exports don’t exist at all?

(Tested in both Chromium and Node)

Plotly control slider with javascript

I took the first plotly’s sliders example https://plotly.com/javascript/sliders/
and added to the page a button that changes the slider position.

It does indeed change the slider but the plot itself is not updated.
It should go on ‘green’ but remains on ‘blue’.

Any suggestions on how to control the slider and the plot using javascript ?

// this is my code
document.getElementById("btn").onclick = () => {
    let newl = document.getElementById('graph').layout
    newl.sliders[0].active = 1
    Plotly.relayout("graph", newl)
}

// this is the plotly example cut and pasted
Plotly.newPlot('graph', [{
    x: [1, 2, 3],
    y: [2, 1, 3]
}], {
    sliders: [{
        pad: {
            t: 30
        },
        currentvalue: {
            xanchor: 'right',
            prefix: 'color: ',
            font: {
                color: '#888',
                size: 20
            }
        },
        steps: [{
            label: 'red',
            method: 'restyle',
            args: ['line.color', 'red']
        }, {
            label: 'green',
            method: 'restyle',
            args: ['line.color', 'green']
        }, {
            label: 'blue',
            method: 'restyle',
            args: ['line.color', 'blue']
        }]
    }]
}, { showSendToCloud: true });
<script src="https://cdn.plot.ly/plotly-3.0.1.min.js" charset="utf-8"></script>
<div id="btn">Click to change slider's position</div>
<div id="graph"></div>

Yubikey for touchless website authentication

I am currently working on a website for a small set of users. The backend is done using C# and .Net Core, but i don’t think that matters much for this question.

I would like to use a yubikey as following:

  • Without an authorized yubikey present the site should not work (e.g. say “not authorized”).
  • When an authorized key is present, i want each request to be authorized by the key, without any need to press the button on it.

Is this combination (discoverable credentials and also touchless) possible with a yubikey (using webauthn?)?

I thought about maybe handling the authentification in the nginx reverse proxy and then only passing the user to the actual application, is that how you usually do it?

I actually don’t have the yubikey yet, because before buying them i want to make sure this usecase is possible.

I couldn’t find & Setup ESPN Source for Live NFL Shedule

I’m building a website that displays the NFL schedule and I’d like to integrate a free API from ESPN (or any other reliable source) to automatically pull in up-to-date NFL game schedules.

After some research, I couldn’t find any official public ESPN API for NFL schedules, but I noticed some third-party sites or browser dev tools showing ESPN schedule data fetched in JSON format (e.g., from endpoints like site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard). I’m not sure if using this kind of data is allowed or if there’s a better/official way to do it.

Here’s what I want to know:

Is there a public or unofficial ESPN API that I can legally use to fetch NFL schedule data?

If yes, how can I fetch and display this data on my website (e.g., using JavaScript or PHP)?

Are there alternative free APIs or data sources you recommend for NFL schedules?

I want to keep it legal, reliable, and ideally free. Any guidance or examples would be much appreciated!

mediapipe custom pose connections

I am using mediapipe with javascript. Everything works alright until i try to show connections between spesific landmarks (in my case bettween landmarks 11, 13, 15, 12, 14, 16)

here is my custom connections array:

const myConnections = [
    [11, 13], // Left Shoulder to Left Elbow
    [13, 15], // Left Elbow to Left Wrist
    [12, 14], // Right Shoulder to Right Elbow
    [14, 16], // Right Elbow to Right Wrist
];

here is how i call them

// Draw connections
      drawingUtils.drawConnectors(landmarks, myConnections, { color: '#00FF00', lineWidth: 4 });

I can draw only the landmarks i want, but not the connections between them. I tried logging the landmarks to see if they aren’t recognised, and they returned values for X, Y, Z with VISIBILITY being UNDEFINED

console.log("Landmark 11 (Left Shoulder):", landmarks[11].visibility);
      console.log("Landmark 13 (Left Elbow):", landmarks[13].x);
      console.log("Landmark 15 (Left Wrist):", landmarks[15].y);

I tried changing the array to something like the code below and call them with the

drawingUtils.drawConnectors()

but it didnt work.

const POSE_CONNECTIONS = [
    [PoseLandmarker.LEFT_SHOULDER, PoseLandmarker.LEFT_ELBOW],
    [PoseLandmarker.LEFT_ELBOW, PoseLandmarker.LEFT_WRIST],
    [PoseLandmarker.RIGHT_SHOULDER, PoseLandmarker.RIGHT_ELBOW],
    [PoseLandmarker.RIGHT_ELBOW, PoseLandmarker.RIGHT_WRIST]
];

I used some generated code with a previous version of the mediapipe api (pose instead of vision) and it was working there

Unable to access supabase database

I have a Next.js app where I use Supabase’s createClient to connect to my database. The connection setup works fine, and the client initializes correctly.

However, when I try to query a table using .from(‘TableName’).select(‘*’), the request fails with a TypeError: fetch failed error. The error response is given at the end

The strange thing is that this code was working perfectly until today, and no changes were made to the code or environment variables.

This is the part of the Code which has the errors:

  console.log("DEBUG: SUPABASE_URL from process.env:", process.env.SUPABASE_URL!);
  console.log("DEBUG: SUPABASE_ANON_KEY from process.env:",process.env.SUPABASE_ANON_KEY!);

  const supabase = createClient(
    process.env.SUPABASE_URL!,
    process.env.SUPABASE_ANON_KEY!,
    { db: { schema: 'data' } }
  );
  console.log(supabase);
  const { data: drivers, error: driverError } = await supabase.from("Driver Info").select('*');
  console.log(driverError)

The Error:

{
    "message": "TypeError: fetch failed",
    "details": "TypeError: fetch failedn    at node:internal/deps/undici/undici:13178:13n    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)n    at async InstrumentsPage (C:\Work\Programming\webdev\fRank\foneranked\.next\server\chunks\ssr\[root-of-the-server]__b68c1b2a._.js:82:51)",
    "hint": "",
    "code": ""
}

Is it possible to create one ClipboardItem with both MIME types?

I am trying to copy the URL of my page and embed it to HTML text, which wherever this mime is supported it shows the HTML text and we can open the URL by clicking the text (which I’ve already made possible).

The issue is with unsupported fields, for example google search, simple editors etc.
I have tried adding another mime type (text/plain) in addition to text/html so it saves both types and pastes the HTML text whenever it is supported and only the URL wherever it is not supported (of course this is the desired state).
But it still does not work.

The js file looks something like this :”

window.copyLinkWithText = (url, visibleText) => {
try {

    const htmlSnippet = `<a href="${url}">${visibleText}</a>`;
    const plainTextSnippet = url; // Just the URL in plain text

    const blobHtml = new Blob([htmlSnippet], { type: 'text/html' });
    const blobText = new Blob([plainTextSnippet], { type: 'text/plain' });

    const clipboardItemInput = new ClipboardItem({
        'text/html': blobHtml,
        'text/plain': blobText
    });

    navigator.clipboard.write([clipboardItemInput])
        .then(() => console.log("Copied both HTML and plain text to clipboard"))
        .catch(err => console.error("Error copying to clipboard:", err));
}
catch (ex) {
    console.error("Exception in copyLinkWithText:", ex);
}

};

Anyone knows what the problem is? And if it’s possible or not?

A better way to compensate for JavaScript client time-zone offset and locale, for ASP.NET Web API

Recently our QA discovered a bug where the date captured in a Vue.js three-field DoB (Date of Birth) editor control (Day, Month, Year), started to arrive at the ASP.Net Web API with a value as the day before what is entered, and also with a time of 2300 hours.

This appeared to happen after we started to store dates as as JavaScript Date object in the DoB editor Vue.js control instead of the date as a JS string, but only came to light recently as we (in the UK) moved to Summer daylight saving hours (BST) from Winter GMT. The DoB editor takes the values in its fields and provides the value back to the parent Vue, also as a JS Date.

Using various Stack Overflow solutions, I basically arrived at the following solution, which does work and allows the user entered date to arrive at the Web API with the correct value.

The web API controller endpoint declaration looks like this:

[HttpPost("authenticate")]
public async Task<IActionResult> Authenticate(PatientAuthenticationRequestDTO dto)
{
...

The DTO looks like this:

public class PatientAuthenticationRequestDTO
{
    [Required]
    [MaxLength(10)]
    public string PatientNumber { get; set; }

    [Required]
    public DateTime DateOfBirth { get; set; }
}

The value in question is stored in the DateOfBirth property

The date value is held in the following property of a structure: this.form.dateOfBirth

// Convert the date of birth to ISO for the API call
const dateOfBirthWithClientOffset = this.form.dateOfBirth;
const clientOffsetOffsetModifier = -dateOfBirthWithClientOffset.getTimezoneOffset();
const ticksMultiplier = 1000;
const secondsMultiplier = 60;
const dateOfBirthWithClientOffsetInTicks = dateOfBirthWithClientOffset.getTime() + clientOffsetOffsetModifier * ticksMultiplier * secondsMultiplier;
const dateOfBirthWithClientOffsetInUTC = new Date(dateOfBirthWithClientOffsetInTicks);
const dateformattedForDotNetSerialisation = dateOfBirthWithClientOffsetInUTC.toISOString();

// Call the API to authenticate the patient
this.$http.post(this.$endpoints.api.patient.authenticate, { patientNumber: this.form.patientNumber, dateOfBirth: dateformattedForDotNetSerialisation })
                    .then((response) => {
    ...

This solution, although working, feels very heavy handed and just plain wrong. Surely there is a more succinct way to send a JavaScript data to an ASP.Net Web API, and take into consideration locale and daylight saving?