Getting ‘Bad request, missing form’ error when sending requests to Express app deployed on Netlify

Using Netlify CLI i typed netlify deploy --prod in my express app and i get:

✔ Finished uploading blobs to deploy store
✔ No cached functions were found
✔ Finished hashing
✔ CDN requesting 0 files
✔ Finished uploading 0 assets
✔ Deploy is live!

Build logs:        https://app.netlify.com/abcxyz
Function logs:     https://app.netlify.com/abcxyz/functions
Unique deploy URL: https://app.netlify.com/abcxyzp
Website URL:       https://app.netlify.com/abcxyz

In production i sent for example:

POST http://localhost:3000/api/v1/token

so i tried in POSTMAN:

https://app.netlify.com/abcxyz/api/v1/token

but it didnt work. I get:

Bad request, missing form

My netlify.toml

[functions]
  external_node_modules = ["express"]
  node_bundler = "esbuild"
[[redirects]]
  force = true
  from = "/api/*"
  status = 200
  to = "/.netlify/functions/api/:splat"

and api.ts copied from netlify docs:

import express, { Router } from 'express';
import serverless from 'serverless-http';

const api = express();

const router = Router();
router.get('/hello', (req, res) => res.send('Hello World!'));

api.use('/api/', router);

export const handler = serverless(api);

How to send any request to deployed server on netlify that actually works?

Border outer div depending on inner content

I have a div wrapper .outter which can have any number of .inner-wrapper divs. These have any number .element divs. From level to level there are either the same number of elements or fewer elements. This creates a kind of pyramid at the bottom.

I would like to give the .outter wrapper a border and/or box-shadow. The contours of the .inner-wrapper should be traced directly. Importantly, there should be no border between the red and the blue elements where they touch. I don’t know if this is possible without any complicated calculations using JS.

As I said, it can also happen that red and blue are the same width, i.e. have the same number of elements. However, a lower .inner-wrapper element will never have more elements than an upper .inner-wrapper element.

.outter {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  flex-direction: column;
  border-top: unset;
  overflow: hidden;
  width: auto;
}

.inner-wrapper {
  display: flex;
  justify-content: center;
  width: 100%;
}

.element {
  width: 100px;
  height: 100px;
  background: blue;
}

.element.red {
  background: red;
}
<div class="outter">
  <div class="inner-wrapper">
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
    <div class="element"></div>
  </div>
  <div class="inner-wrapper">
    <div class="element red"></div>
    <div class="element red"></div>
  </div>
</div>

Vite Library Mode Using Query Params inside React App

TL;DR:
When I get a build in my vite js project, there are multiple js files, one of them index.js, which imports my main react script. In my react script how do I get the queries that is entered from the script, tag? index.js can reach them via import.meta.url but how my react app will do it?.

I have created a widget with react, in my react app I get query params from import.meta.url

my script injected into HTML like this <script type="module" src="/src/main.jsx?exampleQuery=123"></script>

it works in dev mode.

but when I build my project,

an index.jscreated which all it’s do is importing my react app like

import "./main-SOMEHASH.js", which means that I’m no longer able to reach to queriesinside my react app, it’s defined in index.js

If I manually change the import statement in index.js to import ./main-SOMEHASH.js?exampleQuery=123 it works.

but I need it to be dynamic.

If I change index.js ‘s content to:

const urlParams = new URLSearchParams(new URL(import.meta.url));
const modelHash = urlParams.get("exampleQuery");
import(`./main-y1A-E6X6.js?exampleQuery=${exampleQuery})`);

Again it’ll work but in this case I’d need to change index.js each time I get a build.

Is there an easier way, or best practice for this?

finally my vite.config.js

  build: {
    minify: "terser",
    lib: {
      entry: "./src/main.jsx",
      name: "Widget",
      fileName: "index",
      formats: ["es"],
    },
  },

Player disconnects from the game due to lost wss connection

WS package is added to our Node js library. We connect to the socket via https with the help of PHP, but our wss server disconnects from time to time. DNS goes through cloudflare. SSL is active on the server side and on cloudflare. We cannot detect the problem of disconnection. What is your suggestion and opinion?

Here is the link section in index.php:

$gameIp = "mydomain.com;
                    $gamePortforFfa = "1001";
                    echo '<option id="vs-1" value="'.$gameIp.'/vs-1">VS-1</option>';

Below is the relevant part in main.js:

function wsConnect() {
        sid = Math.floor(1+Math.random()*1000000);
        wsUrl = "wss://" + CONNECTION_URL;// + "/" + sid;
        nodesOnScreen = [];
        playerCells = [];
        nodes = {};
        nodelist = [];
        Cells = [];
        leaderBoard = [];
        lastWinner = '?';
        this.countdown = 3600;
        mainCanvas = teamScores = null;
        userScoreMax = 0;
        userScoreCurrent = 0;
        teamMapPlayers = [];
        clanMapPlayers = [];
        
        ws = new WebSocket(wsUrl);
        ws.binaryType = "arraybuffer";
        ws.onopen = onWsOpen;
        ws.onmessage = onWsMessage;
        ws.onclose = onWsClose;
        ws.onerror = function () {
            console.log("socket error");
        }
    }

The console records resulting from the disconnection are shown in the images below:

enter image description here

enter image description here

We tried the recommendations suggested as a result of different research. but we could not reach the result.
Additionally, after the player is disconnected from the game, he cannot re-enter the game.
Below is a diagram showing the error log we received with pm2.

enter image description here

My slideshow carousel doesn’t work, I would like it to work manually?

I would like to create a carousel, my images are well-positioned but my carousel doesn’t manually with the provided arrows, there might be some CSS properties which lack to my code. I don’t kown if my javscript code is ok. I also would to style my arrows with CSS properties. Can please have a look at my code below.carousel

HTML

`



“`

CSS

“body {
margin: 0;
padding: 0;
}

.carousel ul {
width: 100%;
height: 100%;
}

.carousel-container .slide {
width: 100%;
height: 100%;
}

.carousel-container {
position: relative;
margin: 0;
padding: 0;
}

.carousel-container button {
position: absolute;
z-index: 1;
top: 50%;
}

.carousel-button-next {
right: 32px;
}

.carousel-button-prev {
left: 32px;
}

.carousel {
position: relative;
}

.carousel ul {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
list-style: none;
}

.slide {
position: absolute;
}

.slide>img {
display: block;
width: 100%;
height: 100%;
}

.carousel-button {
position: absolute;
z-index: 2;
background: none;
border: none;
top: 50%;
cursor: pointer;
padding: 0;
}

.carousel-button:hover,
.carousel-button:focus {
color: white;
}

.carousel-button:focus {
outline: black 1px solid;
}

Javscript

“document.addEventListener(“DOMContentLoaded”, function () {
const carousel = document.querySelector(‘.carousel’);
const nextButton = document.querySelector(‘.carousel-button-next’);
const prevButton = document.querySelector(‘.carousel-button-prev’);
const slides = document.querySelectorAll(‘.slide’);
let currentIndex = 0;

  function nextSlide() {
    currentIndex = (currentIndex + 1) % slides.length;
    updateCarousel();
  }

  function prevSlide() {
    currentIndex = (currentIndex - 1 + slides.length) % slides.length;
    updateCarousel();
  }

  function updateCarousel() {
    const offsetPercentage = -currentIndex * 100;
    carousel.style.transform = `translateX(${offsetPercentage}%)`;
  }

  nextButton.addEventListener('click', nextSlide);
  prevButton.addEventListener('click', prevSlide);
});
</script>`

`
I am looking for a carousel that works manually, I would have liked it to be with autoplay but it’s way to hard for me. I want that when the user clicks on the arrows, the slide changes and goes to the next slide. I would like that you check CSS and add some properties ( especially for the arrows but also the rest of the carousel). Could you also check the javascript I have introduced and correct it so that the carousel works.

Javascript code to display to pictures in one row

I have a javascript code for website and I need the two pictures array to show in one row. I have tried the css flex but that not how we want them to appear

are we able to join two pictures in javascript?

slides[slideIndex-1].style.display = "inline-block";
slides[slideIndex].style.display = "inline-block";

I have tried css flex but since they are scrollable items they move all over the place and we only want them at the center. tried adding a parent class to arrange them in column css but didnt work

ESM MODULE importing with await issue

I’m trying to import in an ESM module with await but when I use the await I don’t get any error but the program stops running

import { predMaintModel } from "../dataBases/index.js";
import predMaint from "../predMaintenance/index.js";

await predMaint()

const getDeviceData = async (req:any, res:any, cont:any) => {
    const { record, currentAdmin } = cont;

    //  const deviceData = devices.find(device=> device.id === req.params.recordId);

    return {
        record: record.toJSON(currentAdmin),
        // deviceData
    };
};

const getAvailableDevices = async (req:any, res:any, cont:any) => {
    const { record, currentAdmin } = cont;
    const devices = await predMaintModel.find({}, { temperature:0,vibration:0 } )

    return {
        devices
    };
};
export default {
    getDeviceData,
    getAvailableDevices
};

I’m expecting to not get promise from my import, I actually have the same structure on other part of my code and it works there.

Regex Quantifier Syntax [duplicate]

I’m learning about Regex in JavaScript and i got to the part of quantifiers where we have quantifiers like {N} that matches the exactly N occurrences, {N,M} that matches at least N and at most M occurrences.

Now i try something like this;

const pattern = /d{3}/
console.log(pattern.test('8845') 

It outputs ‘true’ which is supposed to be ‘false’. also this;

const pattern = /d{3,5}/
console.log(pattern.test('884567')

also outputs true which is also supposed to be false.

Serve up JSON response with Express

I’ve tried serving up a chat-gpt response with Node, I am able to read the data via the function but it wont be served up by the server, only returning {}.

index.js

import gptSummary from "./gptFunc.js";
import express from "express";

const app = express();

app.use(express.static("./public"));
app.use(express.urlencoded({ extended: true }));

app.post("/", async (req, res) => {
  let data = req.body.input;
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(gptSummary(data)));
});

app.listen(8080, () => {
  console.log("Server running on port 8080");
});

gptFunc.js

import OpenAI from 'openai';

export default async function gptSummary(content){
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY
    });

    const chatCompletion = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages:[{"role": "system", "content": "you must summarize the following text in a concise way. Do not include any extraneous information or add any additional information"}, {"role": "user", "content": content}],
    });
  let response = chatCompletion.choices[0].message;
  return response;
}

/public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>
  <form method="post">
    <label for="input">Enter Text</label><br/>
    <input type="text" name="input" placeholder="type..."/>
    <input type="submit" value="generate">
  </form>
</body>
</html>

I tried different alterations with how I returned the response however it seemed to have no effect. I believe that it is with how the content is served (I would prefer it to be json, so that I can read it easier later on).

I tried res.send(JSON.stringify(gptSummary(data))); as well as res.json

React JS – Tanstack/React-Table Infinite loop when i access selected row outside of table component

Hello i am using shadcn table with tanstack table and while trying to access the selected rows outside of Table component i get infinite loop error, is there another way ? except using refs and onRowSelectionChange method

function TableComponent ({columns, data, paginationProps, setSelectedRows}){

const manualPagination = useMemo(() => !!paginationProps, [paginationProps]);
const [rowSelection, setRowSelection] = useState({});
const [pagination, setPagination] = useState({
pageIndex: 0,
pageSize: manualPagination
? paginationProps?.rowsPerPage || 0
: data.length,
});

const table = useReactTable({
data,
columns: columns,
pageCount: manualPagination ? paginationProps?.totalPages : undefined,
manualPagination,
state: {
rowSelection,
pagination,
},
getRowId(originalRow: any) {
return originalRow.id;
},
getCoreRowModel: getCoreRowModel(),
onPaginationChange: (updater) => {
setPagination(updater);
},
onRowSelectionChange: (updater) => {
setRowSelection(updater);
},
getPaginationRowModel: getPaginationRowModel(),
});

const rows = table.getSelectedRowModel().rows;

useEffect(() => {
console.log('Re Render') // Re-Renders Normal;
}, [rows])

// ! INFINITE LOOP
useEffect(() => {
console.log('Re Render 2') // I get error of infinite loop
setSelectedRows?.(rows.map((row) => row.original));
}, [rows]);

}

function ParentComponent (props){
const [selectedRows, setSelectedRows = useState ([])

useEffect(() =>{
// do your custom handle of the selection
},[selectedRows])

return (
<Table
columns={columns}
data={data}
setSelectedRows={setSelectedRows}>
/>
......
)

}

I tried using useRefand onPaginationChange and it works but useref won’t detect change and onPaginationChange needs settimeout

Update JSONB column don’t works (Supabase)

I have developed this function to perform an update of digital_wallet column with Supabase. The table digital_wallets have 2 columns: user_id and digital_wallet. And I have no error in console.

export const updateDigitalWallet = async (newDigitalWallet: DigitalWallet, userId: string) => {
  try {
    const { data, error } = await supabase
      .from(Tables.DigitalWallets)
      .update({ digital_wallet: newDigitalWallet }, { count: 'exact' })
      .eq('user_id', userId)
      .select()

    if (error) throw error

    console.log(data)

    return true
  } catch (error) {
    console.error((error as PostgrestError).message)
    return false
  }
}

data is null and I dont understand why it’s don’t working correctly (I have no change in Table Editor). Thanks in advance for any help from you!

Querying data with pg-cursor

I have the following code to read the first 10 rows from a query with a PG Cursor:

const client = new Client(`<DATABASE URL>`)
await client.connect()
const cursor = client.query(new Cursor(queryString))
let rows = await cursor.read(10)
cursor.close(() => client.release())

However, this is returning the following:

ReferenceError: setImmediate is not defined
    at Cursor2._sendRows (file:///Users/neil/code/console-query-runner/node_modules/pg-cursor/index.js:120:5)
    at Cursor2.handlePortalSuspended (file:///Users/neil/code/console-query-runner/node_modules/pg-cursor/index.js:140:10)
    at Client2._handlePortalSuspended (file:///Users/neil/code/console-query-runner/node_modules/pg/lib/client.js:372:22)
    at emitOne (node-modules-polyfills:events:84:13)
    at Connection.emit2 [as emit] (node-modules-polyfills:events:171:7)
...

I can’t see what the issue might be here, as setImmediate isn’t used anywhere in the code, and the code I have matches the examples pretty closely. What am I missing here?

Button does not print a string on the dev console [closed]

I am trying to test if my button is working by logging a text on the dev console. But when I click on the button I don’t see it printing on the console.

import { Component, EventEmitter, Input, Output } from '@angular/core';
  import { CommonModule } from '@angular/common';

  @Component({
  selector: 'app-button',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './button.component.html',
  styleUrl: './button.component.css',
})
export class ButtonComponent {
  @Input() text!: string;
  @Input() color!: string;
  @Output() btnClick = new EventEmitter();

  onClick() {
    this.btnClick.emit();
  }
}
 <button
   [ngStyle]="{ 'background-color': color }"
   class="btn"
   (click)="(onClick)"
 >
   {{ text }}
</button>
<header>
  <h1>{{ title }}</h1>
  <app-button
   color="green"
   text="Add"
   (btnClick)="toggleAddTask()"
  ></app-button>
</header>
 import { Component } from '@angular/core';
 import { ButtonComponent } from '../button/button.component';

 @Component({
   selector: 'app-header',
   standalone: true,
  templateUrl: './header.component.html',
  styleUrl: './header.component.css',
  imports: [ButtonComponent],
})
export class HeaderComponent {
  title: string = 'Task Tracker';

  toggleAddTask() {
    console.log('Toggleee Toggleee');
  }
}

I tried to test if my button worked by printing something on the dev console.

How can I use JavaScript in my Blazor server razor page; to change styling on blazor bootstrap button when a form is submitted

My project is a Blazor server application. The fuctionality I am trying to achieve is I want my accordion header to change to the color red if my validation fails (if there is nothing in my input).

enter image description here

//my index.razor page:

@page "/"
<style>


</style>
<PageTitle>Blazor Bootstrap - Home</PageTitle>
<div class="test1">
    <EditForm Model="@registration" OnValidSubmit="HandleFormSubmission">
        <DataAnnotationsValidator />
        <Accordion>
            <AccordionItem Title="Accordion Item #1">
                <Content>
                    <InputText id="SmtpHost" @bind-Value="@registration.SmtpHost" placeholder="SMTP Host" />
                    <ValidationMessage For="@(() => registration.SmtpHost)" />
                </Content>
            </AccordionItem>
        </Accordion>
        <button type="submit">Submit</button>
    </EditForm>
</div>

@code {
    [Inject]
    protected IJSRuntime JSRuntime { get; set; }
    Data.Registration registration = new();
    bool isValidationError = false;
    bool isFormSubmitted = false;
    bool hasRendered = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
                // await Task.Yield();
                // await ToggleAccordionButtonError();
        }
    }

    public async Task HandleFormSubmission(EditContext context)
    {
        Console.WriteLine("Form Submitted Successfully");
        isValidationError = !context.Validate();

        Console.WriteLine("Testing");
        Console.WriteLine(isValidationError);

        if (isValidationError)
        {
            isFormSubmitted = true;
            if (hasRendered)
            {
                ToggleAccordionButtonError();
            }
            else
            {
                StateHasChanged(); // Notify Blazor to re-render the component
            }
        }
    }

    private async Task ToggleAccordionButtonError()
    {
        try
        {
            await JSRuntime.InvokeVoidAsync("toggleAccordionButtonError");
            await JSRuntime.InvokeVoidAsync("myJavaScriptFunction");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error invoking JavaScript function: {ex.Message}");
        }
    }
}

my custom.js file:

console.log("File recognised");

function myJavaScriptFunction() {
    // Invoke an alert
    console.log("Hello from JavaScript!");
}

// .test1 .accordion-button
function toggleAccordionButtonError() {
    console.log("Hello from JavaScript!");
    var elements = document.querySelectorAll('.accordion-button.collapsed');
    elements.forEach(function (element) {
        element.style.backgroundColor = "red";
        element.style.color = "white";
    });
}

My custom.js does work
I am aware I have commented out my code

One solution , I thought of was to use Javascript interobilty with HandleFormSubmission ;however it does’nt seem to work

I do know of Blazor’s Prerendering is a feature in Blazor that allows components to be rendered on the server before being sent to the client, and it imposes certain restrictions on when JavaScript interop calls can be made. Is there a way around this issue . Any insight will be highly appreciated.