How to call store procedure by using javascripts?

server.js :

const express = require('express');
const mysql = require('mysql2');
const path = require('path');
const app = express();

app.use(express.json());

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'db_name',
});

// Connect to MySQL
db.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err);
    return;
  }
  console.log('Connected to MySQL database');
});

// Serve static files (HTML, CSS, JS) from the 'public' folder
app.use(express.static('public'));

// Serve index.html at root
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html'));
});

// Serve home.html at /home
app.get('/home', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/home.html'));
});

// Serve about.html at /about
app.get('/about', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/about.html'));
});


app.get('/get-data', (req, res) => {
  db.query('SELECT * FROM Weather_Stations', (err, results) => {
    if (err) {
      res.status(500).send('Error fetching data from Weather_Stations');
      return;
    }
    res.json(results);
  });
});
// API endpoint to get station_id values from Weather_Stations for Weather_Data table
app.get('/get-station-ids', (req, res) => {
  db.query('SELECT station_id FROM Weather_Stations', (err, results) => {
    if (err) {
      console.error('Error fetching station IDs:', err);
      res.status(500).send('Error fetching station IDs');
      return;
    }
    res.json(results);
  });
});

// API endpoint to get data from Weather_Data
app.get('/get-weather-data', (req, res) => {
  db.query('SELECT * FROM Weather_Data', (err, results) => {
    if (err) {
      console.error('Error fetching Weather_Data:', err);
      res.status(500).send('Error fetching Weather_Data');
      return;
    }
    res.json(results);
  });
});
// --------------------------------- Genarate Weather ID --------------------------------------------
app.get('/generate-weatherData-id', async (req, res) => {
  try {
    const [result] = await db.query("CALL region_id_gen(?)", ['WD']);
    const generatedId = result[0]?.NextNumber || null; // Extract the ID from the result
    if (generatedId) {
      res.status(200).json({ weatherData_id: `WD-${generatedId}` });
    } else {
      res.status(500).json({ error: 'Failed to generate weatherData_id' });
    }
  } catch (error) {
    console.error("Error generating weatherData_id:", error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// --------------------------------- Start the Server --------------------------------------------
app.use((req, res, next) => {
  console.log(`Request URL: ${req.url}`);
  next();
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

error:

Server is running on port 3000
Connected to MySQL database

You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require(‘mysql2/promise’) instead of ‘mysql2’ for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://sidorares.github.io/node-mysql2/docs#using-promise-wrapper, or the mysql2 documentation at https://sidorares.github.io/node-mysql2/docs/documentation/promise-wrapper

Error generating weatherData_id: Error: You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require(‘mysql2/promise’) instead of ‘mysql2’ for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://sidorares.github.io/node-mysql2/docs#using-promise-wrapper, or the mysql2 documentation at https://sidorares.github.io/node-mysql2/docs/documentation/promise-wrapper

at Query.then (C:UsersPramudith RanganaDocumentsJavaScript ProjectsmySqlDataShownode_modulesmysql2libcommandsquery.js:43:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

How to build a server to bypass CORS errors in accessing third-party API data with a React frontend?

I have a React project where I was able to access basic read-only data from a third-party API without building any backend in my project.

However I’m also trying to access a url on the same site using the following code:

import axios from "axios";
import * as cheerio from "cheerio";

export const fetchReports = async(url) => {
    axios.get(url)
        .then(response => {
            const html = response.data;
            const $ = cheerio.load(html);
            const report = $("div.rw-report__content").text()
            console.log(report);
        })
        .catch(console.error);
}

Running this code by itself works perfectly (of course, on specifying the url instead of passing it as a parameter).

However, when I try to export this function and use it inside useEffect() in my React frontend, I get CORS errors, which look like this (React StrictMode is enabled):
enter image description here

Here is my useEffect():

    useEffect(() => {
//THE BELOW FUNCTION WORKS PERFECTLY FINE WHILE ACCESSING THE THIRD-PARTY API
        fetchAllDisasters()
            .then(response => {
                setTotalDisasterCount(response.data.totalCount)
            });

        fetchOngoingDisasters()
            .then(response => {
                response.data.data.forEach(disaster => {
                    fetchDisasterReport(Number(disaster.id))
                        .then(response => {
//THIS FUNCTION fetchReports() IS WHERE THE CORS ERROR GETS INTRODUCED
                            fetchReports(response.data.data[0].fields.url)
                                .then(response => {
                                    console.log(response)
                                })
                        })
                })
            });
    }, []);

I have tried to build an express server to reroute requests and avoid the cors errors but for some reason I just cannot get it to work despite delving into all tutorials and articles across the internet.

I feel like I’m missing something simple and would really appreciate some guidance on solving this.

How can I implement row-count in DataTables when the results are paginated?

I use DataTables to paginate and order a table containing user data.

The full data set comes from a MySQL database via a .NET application.

The first column of the table has to contain the (current) row count in a manner that would make the count “immune” to rearranging the rows (sorting, in other words). This is why I have used a CSS-based row count, as visible below:

new DataTable('#employees', {
  info: false,
  paging: true,
  "aLengthMenu": [5, 10, 20],
  // "dom": 'rtip',
});
.dt-column-order:before {
  margin-bottom: 1px;
}

th {
  outline: none !important;
}

.dt-paging {
  margin-top: 15px !important;
}

.pagination {
  justify-content: flex-end;
}

/* CSS row count */
table {
  counter-reset: row-num;
}

table tbody tr {
  counter-increment: row-num;
}

table tbody tr td:first-child::before {
  content: counter(row-num) "";
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.datatables.net/2.1.8/js/dataTables.min.js"></script>
<script src="https://cdn.datatables.net/2.1.8/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/2.1.8/css/dataTables.bootstrap5.min.css" rel="stylesheet" />

<div class="container-fluid my-2">
  <h2>Data Tables</h2>
  <table id="employees" class="table table-bordered table-striped mx-1">
    <thead>
      <tr>
        <th>No</th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011-04-25</td>
        <td>$320,800</td>
      </tr>
      <tr>
        <td></td>
        <td>Garrett Winters</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>63</td>
        <td>2011-07-25</td>
        <td>$170,750</td>
      </tr>
      <tr>
        <td></td>
        <td>Ashton Cox</td>
        <td>Junior Technical Author</td>
        <td>San Francisco</td>
        <td>66</td>
        <td>2009-01-12</td>
        <td>$86,000</td>
      </tr>
      <tr>
        <td></td>
        <td>Cedric Kelly</td>
        <td>Senior Javascript Developer</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2012-03-29</td>
        <td>$433,060</td>
      </tr>
      <tr>
        <td></td>
        <td>Ștefan Popa</td>
        <td>Accountant</td>
        <td>Tokyo</td>
        <td>33</td>
        <td>2008-11-28</td>
        <td>$162,700</td>
      </tr>
      <tr>
        <td></td>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
        <td>61</td>
        <td>2012-12-02</td>
        <td>$372,000</td>
      </tr>
      <tr>
        <td></td>
        <td>Herrod Chandler</td>
        <td>Sales Assistant</td>
        <td>San Francisco</td>
        <td>59</td>
        <td>2012-08-06</td>
        <td>$137,500</td>
      </tr>
      <tr>
        <td></td>
        <td>Rhona Davidson</td>
        <td>Integration Specialist</td>
        <td>Tokyo</td>
        <td>55</td>
        <td>2010-10-14</td>
        <td>$327,900</td>
      </tr>
      <tr>
        <td></td>
        <td>Colleen Hurst</td>
        <td>Javascript Developer</td>
        <td>San Francisco</td>
        <td>39</td>
        <td>2009-09-15</td>
        <td>$205,500</td>
      </tr>
      <tr>
        <td></td>
        <td>Sonya Frost</td>
        <td>Software Engineer</td>
        <td>Edinburgh</td>
        <td>23</td>
        <td>2008-12-13</td>
        <td>$103,600</td>
      </tr>
      <tr>
        <td></td>
        <td>Jena Gaines</td>
        <td>Office Manager</td>
        <td>London</td>
        <td>30</td>
        <td>2008-12-19</td>
        <td>$90,560</td>
      </tr>
      <tr>
        <td></td>
        <td>Quinn Flynn</td>
        <td>Support Lead</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2013-03-03</td>
        <td>$342,000</td>
      </tr>
    </tbody>
  </table>
</div>

There is a problem with this solution though: whenever the results set is big enough so that there is pagination, the row count starts at 1 for every page.

So, I actually need a row count based on JavaScript, which would not reset the count for every page. I did not find a way to do this bult into DataTables.

Questions

  1. Is there a built-in DataTables solution to this?
  2. If not, what would be a viable solution to the problem?

webBluetooth API not responding

After successfully connecting to Bluetooth on a Mac with Google Chrome, disconnecting through the system Bluetooth and then reconnecting, the webbluetooth API may easily become unresponsive. What is the reason for this and is there a solution?

After disconnecting the system Bluetooth, connect to Bluetooth through webbluetooth in the browser, hoping to connect normally. In fact, there is no such problem in Google Chrome on Windows computers.

Resolving SHA-1 Error and ‘unable to load script’ in Lerna React Native Project

I have started a lerna project using npx lerna init

package.json

{
  "name": "root",
  "private": true,
  "scripts": {
    "start:gamecenter": "cd packages/GameCenter && react-native run-android --port=8083"
  },
  "workspaces": {
    "packages": ["packages/*"],
    "nohoist": [
      "**/react-native",
      "**/react-native/**"
    ]  },
  "dependencies": {},
  "devDependencies": {
    "lerna": "^8.1.9"
  }
}

lerna.json

{
  "$schema": "node_modules/lerna/schemas/lerna-schema.json",
  "version": "0.0.0",
  "packages": [
    "packages/*"
  ],
  "npmClient": "yarn"

}

in packages section I have created 2 react native project named Bingo , GameCenter

without changing metro config I get the following error;

 ERROR  ReferenceError: SHA-1 for file C:UsersFatihDesktopnewtestnode_modules@react-nativejs-polyfillsconsole.js is not computed.
         Potential causes:
           1) You have symlinks in your project - watchman does not follow symlinks.
           2) Check `blockList` in your metro.config.js and make sure it isn't excluding the file path.
    at DependencyGraph.getSha1 (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcnode-hasteDependencyGraph.js:181:13)
    at Transformer._getSha1 (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcBundler.js:15:26)
    at Transformer.transformFile (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcDeltaBundlerTransformer.js:92:19)
    at Bundler.transformFile (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcBundler.js:43:30)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.transform (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrclibtransformHelpers.js:134:12)
    at async transform (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcDeltaBundlerGraph.js:164:26)
    at async visit (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcDeltaBundlerbuildSubgraph.js:82:29)
    at async Promise.all (index 1)
    at async buildSubgraph (C:UsersFatihDesktopnewtestpackagesBingonode_modulesmetrosrcDeltaBundlerbuildSubgraph.js:103:3)

when I updated the metro.config.js as following

const path = require('path');

module.exports = {
  projectRoot: __dirname,
  watchFolders: [path.resolve(__dirname, '../../node_modules')],
  resolver: {
    blockList: [/.*/node_modules/.*/node_modules/react-native/.*/],
  },
};

I get the following error

unable to load script make sure you re either running metro ( run npx react-native start) or that your bundle index.android.bundle is packaged correctly for release

I did not modify any react native files How may I solve the issue

React native 0.76.5
node v20.18.0
"lerna": "^8.1.9"

Updating ESBuild from 0.24.0 to 0.24.1 throws strange errors

I am using tsup, which uses ESbuild, to build my libraries. Example: https://github.com/react18-tools/turborepo-template/actions/runs/12427963648/job/34698706616

When I tried investigating, I found that only changes in pnpm-lock file reflected update of ESBuild from 0.24.0 to 0.24.1

Here’s the error:

X [ERROR] Expected identifier but found "import"

    (define name):1:0:
      1 │ import.meta.url

How to fix this issue?

AxiosError: Request failed with status code 500 when sending data from client to database

I am trying to send data from my client-side application to the server using Axios, but I am receiving an error:
AxiosError {message: ‘Request failed with status code 500’, name: ‘AxiosError’, code: ‘ERR_BAD_RESPONSE’}

When I test the same endpoint using Postman, the data is successfully passed to the database without any issues. This suggests that the server and database are functioning correctly, but there might be an issue with the client-side request.

`import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";

    const Signup = () => {
      const [formData, setFormData] = useState({
        fname: "",
        lname: "",
        email: "",
        password: "",
        userType: "customer",
      });
      const navigate=useNavigate()
    
      const handleChange = (e) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
      };
      const handleSubmit = async (e) => {
        e.preventDefault();
        try {
          const res = await axios.post(
            "http://localhost:5000/api/users/register",
            formData,
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          );
          console.log(res.data);
          setFormData({
            fname: "",
            lname: "",
            email: "",
            password: "",
            userType: "customer",
          });
          if(res.status === 201){
            navigate('/login');
          }
        } catch (error) {
          console.error(error);
        }
      };
      return (
        <div className="flex items-center justify-center min-h-screen bg-gray-100">
          <form
            className="w-full max-w-md bg-white p-8 shadow-md rounded-md"
            onSubmit={handleSubmit}
          >
            <h2 className="text-2xl font-bold text-center mb-6">Sign Up</h2>
    
            <div className="mb-4">
              <label
                htmlFor="fname"
                className="block text-gray-700 font-medium mb-1"
              >
                First Name
              </label>
              <input
                type="text"
                id="fname"
                name="fname"
                value={formData.fname}
                onChange={handleChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
                required
              />
            </div>
    
            <div className="mb-4">
              <label
                htmlFor="lname"
                className="block text-gray-700 font-medium mb-1"
              >
                Last Name
              </label>
              <input
                type="text"
                id="lname"
                name="lname"
                value={formData.lname}
                onChange={handleChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
                required
              />
            </div>
    
            <div className="mb-4">
              <label
                htmlFor="email"
                className="block text-gray-700 font-medium mb-1"
              >
                Email
              </label>
              <input
                type="email"
                id="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
                required
              />
            </div>
    
            <div className="mb-6">
              <label
                htmlFor="password"
                className="block text-gray-700 font-medium mb-1"
              >
                Password
              </label>
              <input
                type="password"
                id="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-orange-500"
                required
              />
            </div>
    
            <button
              type="submit"
              className="w-full bg-orange-500 text-white py-2 px-4 rounded-md font-bold hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-orange-500"
            >
              Sign Up
            </button>
          </form>
        </div>
      );
    };
    
    export default Signup;` `const mongoose = require("mongoose");
    
    const UserSchema = new mongoose.Schema(
      {
        fname: {
          type: String,
          required: true,
        },
        lname: {
          type: String,
          required: true,
        },
        email: {
          type: String,
          required: true,
        },
        password: {
          type: String,
          required: true,
        },
        userType: {
          type: String,
          enum: ["admin", "user"],
          default: "user",
        },
      },
      {
        timestamps: true,
      }
    );
    
    module.exports = mongoose.model("User", UserSchema);` `const express = require("express");
    const router = express.Router();
    const User = require("../../models/User");
    const bcrypt = require("bcrypt");
    const jwt = require("jsonwebtoken");
    const authenticateToken = require("../../middleware/auth");
    
    //register
    router.post("/register", async (req, res) => {
      try {
        const salt = await bcrypt.genSalt(10);
        const password = await bcrypt.hash(req.body.password, salt);
        const userobj = {
          fname: req.body.fname,
          lname: req.body.lname,
          email: req.body.email,
          password: password,
          userType: req?.body?.userType || "user",
        };
        const user = new User(userobj);
        await user.save();
        return res.status(201).json(user);
      } catch (error) {
        res.status(500).json({ message: "Something went wrong" });
      }
    });
    module.exports = router;` `require('dotenv').config()
    const express=require('express');
    const app=express();
    const bodyParser=require("body-parser");
    const cors=require("cors");
    const connectDB=require('./config/db');
    
    
    //parse requests
    app.use(bodyParser.json());
    app.use(express.json());
    app.use(cors());
    
    
    //db
    connectDB();
    
    //routes
    //users route
    app.use('/api/users', require('./routes/api/user'))
    
    //task route
    app.use('/api/task', require('./routes/api/task'))
    
    const port=5000;
    app.listen(port, () =>{
        console.log(`Server is running on port ${port}`)
    })`

How to prevent fabric’s PenceilBrush from drawing beyond the specified area

As shown in the figure, the picture is in the group. I draw on the picture. How can I limit the drawing range to within the picture and prohibit drawing outside the picture?enter image description here

As shown in the figure, the picture is in the group. I draw on the picture. How can I limit the drawing range to within the picture and prohibit drawing outside the picture?

scrape the html page after click on a div tag using BeautifulSoup

I got some troubles when scraping the questions and answers from websites:

https://tech12h.com/bai-hoc/trac-nghiem-lich-su-12-bai-1-su-hinh-thanh-trat-tu-gioi-moi-sau-chien-tranh-gioi-thu-hai

The problem is the answer only appear when I click on a div Xem đáp án (scroll down to the end) but it’s not a link, it just a div, I guess it use Javascript event trigger to render content after the click on div.

How can I deal with this with Beautifulsoup. I got confict driver problem with Selenium when I use on Ubuntu.

Thank you

Css of data from CKeditor 5 doesn’t work with Vue3 v-html built-in directive

I’m facing an issue with using CKEditor in a Vue project.
The edited data doesn’t exactly match the displayed content using v-html, some CSS adjustments for images are not working as expected.

<template>
  <div class="editor-container__editor">
    <ckeditor
       v-if="isLayoutReady"
       v-model="editorData"
       :editor="editor"
       :config="config"
    />
  </div>

  <div style="margin: 20px 350px; padding: 10px; border: 1px solid #000">
      <h2>Editor data display:</h2>
      <div v-html="editorData"></div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import {
  ClassicEditor,
  // Others
} from "ckeditor5";
import "ckeditor5/ckeditor5.css";
const isLayoutReady = ref(false);
const editorData = ref("");
const config = {
  // Some configuration
  image: {
    toolbar: [
      "toggleImageCaption",
      "imageTextAlternative",
      "|",
      "imageStyle:inline",
      "imageStyle:wrapText",
      "imageStyle:breakText",
      "|",
      "resizeImage",
    ],
  },
};
const editor = ClassicEditor;

onMounted(() => {
  isLayoutReady.value = true;
});
</script>

I’m pretty sure I’m misunderstanding something and not using ckeditor properly, the css from “ckeditor5/ckeditor5.css” seems to be what makes the editor work, but it won’t apply to the data displayed with v-html, and I’m not sure what I need to do to address this issue.

Node.js Express allowing importing JS modules from local directory outside the app

I would like to share JS code (utilities.js) between web projects on the same server for use between client-side Node.js Express scripts. I’m trying to utilize ES6 module imports for this purpose.

The problem is: it has become apparent that my Express set-up doesn’t permit imports from outside the working express.static directory (i.e. /public, “client-side”).

I can achieve module import through various approaches, but as soon as I put utilities.js above public an import call from within script.js cannot access it.

-app.js
-project
-project
-project
–index.js
–public
—script.js
-utilities
–utilities.js

in app.js:

express.static(`./project/public`)(req, res, next);
app.use(`/project`, `./project/index.js`);

in html:

<script type="importmap">
  {
    "imports": {
      "u": "./../../utilities/utilities.js"
    }
  }
</script>

in script.js:

import wow from 'u';
alert(wow.woo());

in utilities.js:

function woo() {
    return "woo";
}
export default { woo };

Question: How can I import (i.e. share) utilities.js between projects?

Ideas: Do I need to add more static routes? Is this a node or express config issue? Is CORS the problem here? Is server -> client browser import just not intended? Should I instead approach like req to index.js -> readFile(‘/path/utilities.js)’ -> dynamic import? Is app.use(express.static(‘utilities’)) a better approach?

How can I use the value of ViewData in my script?

In my PageModel, I am setting the value of ViewData before returning to the view.
When I debug, I see that the ViewData has the expected value, TestingDevelopmentAccountingstatements.png

// .cshtml.cs
public Task<IActionResult>OnGetViewFile(string fileName)
{
  var fileProvider = _fileServerProvider.GetProvider("/Accounting");
  var fileInfo = fileProvider.GetFileInfo(fileName);

  ViewData["FilePath"] = fileInfo.PhysicalPath;
  return Task.FromResult<IActionResult>(this.Page());
}

This is what the .cshtml looks like:

@page
@model AccountingProject.Pages.Statements.Statements_Model
@{
  var filePath = ViewData["FilePath"] as string; // when this is debugged it has the correct value
}

//html here

<script type="text/javascript">
  let viewFileName = '@filePath';  // why is it an empty string here?  How can I set viewFileName to the value of filePath?
  console.log(viewFileName);
</script>

I need to be able to use the value of filePath in the script, but have been unsuccessful. The value either ends up as an empty string or null with whatever I try. I have also tried setting viewFileName to @filePath without the single quotes as well as setting it to @Html.Raw(Json.Serialize(filePath)).

Move the table to the extreme right hand side of the screen

I have two div rows defines and have some elements constrained to it as shown in the code snippet below. The code snippet is not working (showing the jqxwidget library table) as expected for unknown reason as I have the same code working here in this JSFiddle.Hence, I’ve included the fiddle in this post. In the JSFiddle above, it is currently showing like this:

enter image description here

But I want it to be like this (edited version of image below):

enter image description here

Is it possible to achieve the same with two rows approach?

$('[name="seqlineupspendinglist"]').select2();

var source = {
  localdata: "",
  datafields: [{
    name: 'Name',
    type: 'string'
  }, {
    name: 'Color',
    type: 'string'
  }, {
    name: 'plateName',
    type: 'string'
  }, {
    name: 'date',
    type: 'date'
  }],
  datatype: "array"
};

var adapter = new $.jqx.dataAdapter(source);
$("#jqxgrid").jqxGrid({
  width: 500,
  theme: 'energyblue',
  source: adapter,
  sortable: true,
  ready: function() {
    $("#jqxgrid").jqxGrid('selectrow', 0);
    $('#jqxgrid').jqxGrid('focus');
  },
  columns: [{
    text: 'Name',
    datafield: 'Name',
    columngroup: 'Name',
    width: 90
  }, {
    text: 'Color',
    columngroup: 'Color',
    datafield: 'Color',
    width: 90
  }, {
    text: 'Plate Name',
    datafield: 'plateName',
    width: 170
  }, {
    text: 'Date',
    datafield: 'date',
    width: 160,
    cellsformat: 'dd-MMMM-yyyy'
  }]
});
.row {
  width: 100%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;

}

.block {
  padding: 5px 1%;
}

input {
  display: block;
  height: 22px;
  /* so same height as select */
  border-radius: 4px;
}

input[type="submit"] {
  height: 28px;
  /* so button is same height as select and inputs */
  margin-right: 100px
}

select {
  width: 150px;
  /* so --Please Select-- text is all visible */
}
<script src="https://jqwidgets.com/public/jqwidgets/jqx-all.js"></script>
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.energyblue.css" rel="stylesheet" />
<link href="https://jqwidgets.com/public/jqwidgets/styles/jqx.base.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="row">
  <div class="block">
    <label class="label" for="startLane">Select Dropdown:</label>
    <select name="seqlineupspendinglist">
      <option value="-">--Please Select--</option>
    </select>
  </div>
  <div class="block">
    <label class="label" for="startLane">Starting Lane #:</label>
    <input type="text" id="startLane" name="startLane" />
  </div>
  <div class="block">
    <label class="label" for="endLane">Ending Lane #:</label>
    <input type="text" id="endLane" name="endLane" />
  </div>
  <div class="block">
    <input type="submit" value="Show Cases" />
  </div>
  <div class="block">
    <div>
      <label class="label">Information:</label>
    </div>
    <div>
      <div id="jqxgrid"></div>
    </div>
  </div>
</div>

<div class="row">
  <div class="block">
    <label class="label" for="startLane">Second Row Test</label>
    <input type="text" id="startLane" name="startLane" />
  </div>
  <div class="block">
    <label class="label" for="startLane">Second Row Test</label>
    <input type="text" id="startLane" name="startLane" />
  </div>
  <div class="block">
    <label class="label" for="endLane">Second Row Test</label>
    <input type="text" id="endLane" name="endLane" />
  </div>

</div>

Fetch API taking suspiciously long to get response

I have a server using Express to respond to HTTP requests. It doesn’t give a single response, but rather it makes multiple write calls over time to give status updates. In the browser, the HTTP request is made using the fetch API. The response body is iterated over asynchronously.

All of this works fine except for one issue. The time it takes to await the response from the fetch call is about 8 seconds. I know that the first chunk sent by the server does not take 8 seconds. I have even compared to XHR, which is taking less than 50ms for the progress event to fire. Is there anything I can do to make the initial fetch promise resolve sooner?

Server Code

app.post("/bulk-update", (req, res) => {
  buildTask(req.body, 5, (status) => {
    const completed = status.success + status.error;
    const remaining = status.total - completed;

    if (remaining === 0) {
      res.write(`${JSON.stringify(status)}n`);
      res.end();
      return;
    }

    if (completed % 10 === 0) {
      res.write(`${JSON.stringify(status)}n`);
    }
  });
});

Browser Code


let jobStartTime = Date.now();
const response = await fetch(`/bulk-update`, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body,
});
console.log("end request", Date.now() - jobStartTime); // <-- this is logging 8000ms

const stream = response.body.pipeThrough(new TextDecoderStream());

let buffer = "";
for await (const chunk of stream) {
  buffer += chunk;

  const lines = buffer.split("n");
  buffer = lines.at(-1);
  for (let i = 0; i < lines.length - 1; i++) {
    const line = lines[i];
    const status = JSON.parse(line);
    updateProgress(status);
  }

  if (buffer.trim().length > 0) {
    const status = JSON.parse(buffer);
    updateProgress(status);
  }
}