getting req.body ReadableStream in nextjs14 app routing

I’m trying to get req.body in api but getting ReadableStream.

my code looks like:

// src/app/api/posts/route.js

export async function POST(req, res) {
    console.log('Post request received');
    console.log(req.body);


    return Response.json({
        "success": true,
        "data": req.body,
        "message": "Fetched successfully"
    });
}

expected

//console log
{'title':'test blog'}

but getting

// console log
ReadableStream { locked: false, state: 'readable', supportsBYOB: false }

its on nextjs 14.0.4 and app routing

How to make successful google login using puppeteer in headless: true mode on vercel/render?

I am trying to make google login using puppeteer in headless: true mode on vercel/render but getting this error after browser is launched successfully.


TimeoutError: waiting for selector `input[type="password"]:not([aria-hidden="true"])` failed: timeout 60000ms exceeded
    at new WaitTask (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/IsolatedWorld.js:445:34)
    at IsolatedWorld._waitForSelectorInPage (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/IsolatedWorld.js:335:26)
    at Object.internalHandler.waitFor (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/QueryHandler.js:46:83)
    at Frame.waitForSelector (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/Frame.js:420:36)
    at Page.waitForSelector (/vercel/path0/node_modules/puppeteer/lib/cjs/puppeteer/common/Page.js:2318:39)
    at login (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:974:25)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async loadAccount (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:838:13)
    at async upload (/vercel/path0/node_modules/youtube-videos-uploader/dist/upload.js:52:9)

So, is this issue because of google blocking the automated usage of puppeteer. if so, then why it works perfectly on my local with headless as true/false both works in local? or is it because of something else i am missing here which needs to be taken care of while deoploying on this platforms.

I am trying to make google login request and it should log in successfully but it give the above mentioned error instead of successful login

Im unable to send appropriate error message to the client when using multer(upload.any() )

I’m using this middleware to upload files into an AWS S3 bucket. However, there has been a problem: I’m unable to enter Multer’s error block while filtering the type of files in fileFilter.


const multer = require('multer');
const storage = multer.memoryStorage();
const crypto = require('crypto');
const sharp = require('sharp');
const { AwsUploadFile } = require('../../utils/s3');

const generateFileName = (mimeType, bytes = 32) => {
  const extension = mimeType.split('/')[1]; // Extracts file extension from MIME type
  return crypto.randomBytes(bytes).toString('hex') + '.' + extension;
};

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype.startsWith('image/') ||
    file.mimetype.startsWith('video/')
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: { fileSize: 50 * 1024 * 1024 }, // 50MB limit
  fileFilter: fileFilter,
});

async function fileUpload(req, res, next) {
  const multerUpload = upload.any();
  multerUpload(req, res, async (err) => {
    if (err instanceof multer.MulterError) {
      return res.status(500).json({
        success: false,
        message: 'Error uploading file',
        error: err.message,
      });
    } else if (err) {
      // An unknown error occurred when uploading.
      console.log('General error:', err.message);

      return res.status(500).json({
        success: false,
        message: 'An error occurred while processing',
        error: err.message,
      });
    }

    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        success: false,
        message: 'No files uploaded',
      });
    }

    const file = req.files[0];
    const getFileName = generateFileName(file.mimetype);
    file.originalname = file.mimetype.startsWith('video/')
      ? 'public/videos/' + getFileName
      : 'public/images/' + getFileName;

    if (file.mimetype.startsWith('image/')) {
      try {
        const fileBuffer = await sharp(file.buffer)
          .resize({ height: 1920, width: 1080, fit: 'contain' })
          .toBuffer();

        file.buffer = fileBuffer;
      } catch (sharpError) {
        return res.status(500).json({
          success: false,
          message: 'Error processing image',
          error: sharpError.message,
        });
      }
    }

    try {
      const { fileLink, result } = await AwsUploadFile({
        fileBuffer: file.buffer,
        fileName: file.originalname,
        mimeType: file.mimetype,
      });

      req.fileUrl = fileLink;
      req.fileType = file.mimetype.split('/')[0];
      next();
    } catch (awsError) {
      return res.status(500).json({
        success: false,
        message: 'Error uploading to AWS',
        error: awsError.message,
      });
    }
  });
}

module.exports = fileUpload;

If I throw an error, then I am able to get into it, but I’m unable to send these headers:
return res.status(500).json({ success: false, message: 'An error occurred while processing', error: err.message })
when i use cb(null, false) in fileFilter func, Multer skips the file without triggering an error but i want to throw an error if its not a valid file type and i need to send that invalid file type error to the client

Im creating a “sales banner on react using grid and makStyles, but my card and the other description card are not next to each other

As I said, I’m creating a type of sales banner, and I need some information on this banner, my CourseDescription, which is a component that brings all the course information, and my BuyCourseCard, which brings some more information about the sale of the course, however I need them to align and stay next to each other within my main div or grid, but this never happens and I don’t know why.

My code:

     return (
    <Box>
      <Grid>
        <Grid
          className={classes.backgroundDescription}
          item
          container

          xs={12}
          md={12}
        >
          <div
            style={{ 
              position: 'absolute', 
              top: 0, 
              left: 0, 
              right: 0, 
              bottom: 0, 
              zIndex: -1, 
              backgroundImage: `url(${icon})`, 
              backgroundSize: 'cover', 
              backgroundPosition: 'center', 
              height: '100%', 
              filter: 'blur(10px)', }}
            className={classes.contentCourse}
          />
          <div className={classes.CourseDescriptionStyle}>
            <CourseDescription
              onLike={onLike}
              data={info}
              con={icon}
            />
          </div>
          <Grid className={classes.buyCard}
            item xs={12} md={8}>
            <BuyCourseCard
              data={financial}
              onCourseBuy={onCourseBuy}
              info={info}
              signable={signable}
              courseBlocked={courseBlocked}
              ableBuy={ableBuy}
            />
          </Grid>
        </Grid>
      </Grid>
    </Box>
  );
};

    const useStyle = makeStyles((theme) => ({
      backgroundDescription: {
        position: 'relative',
        overflow: 'hidden',
        '&::before': {
          content: '""',
          position: 'absolute',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          filter: 'blur(10px) ',
          zIndex: -1,
        },
        '& > div': {
          position: 'relative',
          zIndex: 1,
        },
      },
      contentCourse: {
        position: 'absolute',
      },
      CourseDescriptionStyle: {
        width: '50%',
      },
    }));

    export default CourseHeader;

The image how it is

My Image

Remembering that I need that card that is down there to go up and be next to the other card

Github Action, getting ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES)

below if the github yml file i’m using, so basically i’m trying to create a local db so i can my unit tests but somehow i’m getting a 1045 error. i’ve tried already using a no password but still fails

keeps getting

ERROR 1045 (28000): Access denied for user 'user'@'localhost' (using password: YES)
  name: Test node Jest
  on:
    pull_request:
     branches: [test]

  jobs:
    unit-test:
      name: Run Tests
      runs-on: ubuntu-latest
      services:
        mysql: 
          image: mysql:8.0
          env:
            MYSQL_DATABASE: localdb
            MYSQL_USER: user
            MYSQL_ROOT_PASSWORD: testrootpass
            #MYSQL_ALLOW_EMPTY_PASSWORD: yes
          ports:
            - 3306:3306
          options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3
      steps:
        - uses: actions/checkout@v2
        - uses: actions/setup-node@v1
          with:
            node-version: "14"
        - run: npm install
        - name: Set up mysql
          run: | 
            sudo /etc/init.d/mysql start
            mysql -h 127.0.0.1  -u user -ptestrootpass localdb
        - run: npm run test

not sure what I’m doing wrong

How to create an editable textarea field in React JS with options for bold and italics which can parse/save embedded tags in the string

I need a way to display an editable textarea as part of a larger object. This textarea needs to be resizeable, be able to show both bolded and italic text, and also be able to parse values from strings that includes tags. For example, if passed,

<b>the question</b> <i>the answer</i>

It would display

the question the answer

The current code I have set up looks like the following:

    return (
        <textarea
            rows={props.rows}
            name={props.name}
            onChange={(e) => props.setValue(e.target.value)}
            value={props.value || ''}
            style={props.style}
            className={className}
        />
    )

This successfully creates an editable field which would display the above string as

<b>the question</b> <i>the answer</i>

…instead of properly bolding/italicizing it.

How can I create an object which meets these requirements? Either natively or with a library:

  1. Editable field Display text

  2. Allows user to bold/italicize text

  3. Parse strings for bold/italics tags embedded in the string itself

Highcharts zooming makes disappear data

I’m using React and the Highcharts library to create line charts, where all the data comes from the database. Now, for zooming, I’m using the mouse scroll. The issue arises when I zoom in with the scroll multiple times; at a certain point, all the data disappears, and the chart is no longer visible. I’ve checked the console, and no errors are appearing. I’ve tried setting “navigate” to true and noticed that if I choose a range of values that are more current, it doesn’t display any data, but there’s no issue with another range. Do you happen to know a possible solution? Thank you.

Electron silent printing doest resolve promises or async await

I have an app on Electron that is suppposed to print silently with a thermal printer. The main issue here is that the promise is never resolved when the method is called (whether it’s done from the console or the button) when it’s configured on silent.

Here are the codes for the call

ipcMain.on("print", async (event, html) => {
    try {
      let impresion = new BrowserWindow({ show: false }); //Se crea la ventana de impresión invsible para el usuario
      impresion.loadURL(
        "data:text/html;charset=UTF-8," + encodeURIComponent(html)
      ); //Se carga el contenido HTML proporcionado en la ventana oculta
      impresion.webContents.on("did-finish-load", () => {
        //Se espera a que la ventana de impresion termine de cargar el contenido HTML
        impresion.webContents.print(
          //Se especifican opciones de impresion
          {
            printBackground: false,
            silent: true,
          },
          (status, error) => {
            if(status){
              event.sender.send("res-print", { status }); //Envía mensajes indicando el resultado o cualquier error ocurrido
            }else{
              event.sender.send("res-print", error);
            }
            impresion.close();
            win = null;
          }
        );
      });
    } catch (error) {
      //Manejo de errores, en este caso de la impresión de renderizacion
      console.log(error);
      event.sender.send("error-print", { error: error.message });
    }
  });

And the method that works with the button

function imprimirHTML(html) {
    return new Promise(async (resolve, reject) => {
        ipcRenderer.send('print', html);
        console.log('first message');
        ipcRenderer.on('res-print', (event, arg) => {
            console.log('print message');
            resolve(arg);
            console.log(arg);
        });
        ipcRenderer.on('error-print', (event, arg) => {
            console.log('error print message');
            reject(arg)
            console.log(arg);
        });
    })
}

I’ve tried to downgrade the Electron version, using async await, and promises with then and catch, but that doesnt work either…

Iteration through an Iterable Async returns promise instead of result

I’ve been tearing my hair out on this one. I have situation where I retrieve some values from an Azure App Configuration, then assign them to a single settings property inside of a singleton class.

What I’m getting back is a promise. What I want back is an object with each property as a key-value, e.g.:

{
  TESTVAL1: 'Giggity Giggity ;-)',
  TESTVAL2: 'testing123',
  TESTVAL3: 'here we are again'
}

the idea is that when the class is intialized, the settings will be loaded from the Azure App Configuration, and will become available to any other part of the application that uses this code.

The problem lies with this function where I initialize the settings property:

class appConfig {
     private _settings:any // for now
        this._client = new AppConfigurationClient(process.env.AZURE_APPCONFIG_CONNECTION_STRING || '');

     constructor() {
         this._settings = this.loadSettings();
     }

    private loadSettings = async() => {
      let loadedSettings:ConfigVars = {}

      const filteredSettings: AsyncIterableIterator<ConfigurationSetting<string>> = await this._client.listConfigurationSettings({
        labelFilter: process.env.AZURE_CONFIG_LABEL
      });
      for await (const setting of filteredSettings) {
          if (!setting.key.includes(featureFlagPrefix)) {
              const obj:any = {};
              obj[setting.key] = setting.value
              loadedSettings = {...loadedSettings, ...obj}
          }
      }
      return loadedSettings;
    }

}

so – how can I get this to behave so that settings is just an object, not a promise?

Compare List of objects in java script

I want to create a function to compare a list of objects in the fast way

for (let i = 0; i < posts.length - 1; i++) {
  for (let j = i + 1; j < posts.length; j++) {
    const post1 = posts[i];
    const post2 = posts[j];

    if (validation(post1, post2)){
      console.log(`found comparation`);
    }
  }
}

And the validation function compares two fields like this:

const validation = (post1, post2) => post1.need.includes(post2.have) &&
    post2.need.includes(post1.have);

What would be the fastest way to perform this search? These ‘need’ and ‘have’ strings are IDs for a category where I associate them by levels like ‘01030204’. In case it’s useful to know, I’m open to dividing the data based on this, but I’m really looking for ideas on how to improve the speed of this search.

Sending a GET request through js while using Electron

I am trying to send a HTTP GET request to my local flask server but for some reason it doesn’t send. I am trying to build a leaflet map application with Electron and want to send some GET requests from the Electron frontend to the flask backend.

Here is all the code that i am using.

app = Flask(__name__)

@app.route("/locate", methods=['GET'])
def hello_world():
    return "<p>Hello, World!</p>"
function loadShiz(){    
    var Http = new XMLHttpRequest();
    var url = 'http://127.0.0.1:5000/locate';

    Http.onreadystatechange = function() { 
        if (Http.readyState == 4 && Http.status == 200)
            callback(Http.responseText);
    }

    Http.open("GET", url, true);
    Http.send;

    console.log("test 1")
}

loadShiz();
console.log("test 2");

request.js ^^^

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />
        <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

        <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
        <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

        <link rel="stylesheet" href="css/map.css">
    </head>
    <body>
        <div id="map"></div>

        <script type="text/javascript" src="map.js"></script>
        <script type="text/javascript" src="request.js"></script>

    </body>
</html>

Electron map screenshot

You can see that i get the two console.logs but the flask server never gets a request. Whats the deal?

I get the response 200 when i enter the url manually in the search bar of a browser.

Timeout issues with Nodejs MySQL Connection

I am getting a timeout error while trying to connect to my SQL server using node.js mysql package.

Node Version v20.8.0

Code:

// MySQL Internal connection configuration
const connection = mysql.createConnection({
    host: '192.168.8.173',
    user: '[username]',
    password: '[password]',
    database: 'cad'
});

// NMX MySQL connection configuration
const redNMX = mysql.createConnection({
    host: '[ip]',
    user: '[username]',
    password: '[password]',
    database: '[database name]',
    port: '3306',
    connectTimeout: 20000, // Set the connection timeout to 20 seconds (adjust as needed)
});

// Connect to both MySQL servers
connection.connect((error) => {
    if (error) {
        console.error('Error connecting to Local MySQL server:', error);
        return;
    }
    console.log('Connected to Local MySQL server');
    
    // Now that the local connection is established, connect to RedNMX server
    redNMX.connect((redNMXError) => {
        if (redNMXError) {
            console.error('Error connecting to RedNMX MySQL server:', redNMXError);
            return;
        }
        console.log('Connected to RedNMX MySQL server');
        retrieveCallData();
    });
});

function retrieveCallData() {
    console.log("Retrieving call data, line 43.");

    // SQL query to get the latest 10 calls
    const sqlQuery = "SELECT * FROM NFIRSMAIN ORDER BY DATETIMEALARM DESC LIMIT 10";

    redNMX.query(sqlQuery, (error, results, fields) => {
        if (error) {
            console.error('Error retrieving call data from MySQL:', error);
        } else {
            // Process the retrieved call data
            storeNewCalls(results);
        }
        // Close the RedNMX connection (if needed)
        // redNMX.end();
    });
}

I am getting an error output of:

Error connecting to Local MySQL server: Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (C:UsersRyan Pfister – FIRSTDocumentsGitHubCallTrackernode_modulesmysqllibConnection.js:409:13)
at Object.onceWrapper (node:events:628:28)
at Socket.emit (node:events:514:28)
at Socket.emit (node:domain:488:12)
at Socket._onTimeout (node:net:589:8)
at listOnTimeout (node:internal/timers:573:17)
at process.processTimers (node:internal/timers:514:7)
——————–
………….
{
errorno: ‘ETIMEDOUT’,
code: ‘ETIMEDOUT’,
syscall: ‘connect’,
fatal: true
}

What’s weird is I can connect to the server via command line and using MySQL workbench, but not with node.js mySQL package. I have tried specifying the driver type. I looked at the mysql server log as well and did not see anything special.

I tried modifying my code several times, and ensuring there is no firewall blocking access, and that I had the right credentials, all to no luck. ……………………………………………………

How do I pass the element (to get its id) from CKEditor–>uploads()–>_initRequest()?

I have 2 CKEditor fields () in the View.

<div id="editor_1">
     @Html.Raw(@Model.Description_1)
</div>

<div id="editor_2">
     @Html.Raw(@Model.Description_2)
</div>

There is a code that transmits the uploaded image to the controller:

<script>

class MyUploadAdapter {
    
    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                this._initRequest();
                this._initListeners( resolve, reject, file );
                this._sendRequest( file );
            } ) );
    }

    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();
    }
}

</script>

How do I pass in _initRequest() a link to the elements and to understand which field the user is uploading the image to (I need to get the field id)? I tried to figure it out in the controller (in Request class) where I receive the uploaded image, but I couldn’t.

foreach (IFormFile photo in Request.Form.Files)

Thanks!

JavaScript localStorage resets when powering off chromebook

Using JavaScript on a Chromebook, I made a basic localStorage program in p5.js, where you can press keys to add to a variable, and it saves that value to localStorage when it changes:

let amt = 0;

function setup() {
  createCanvas(400, 400);
  if (!!getItem("amt")) {
    amt = getItem("amt");
  }
}

function draw() {
  background(0);
  fill(255);
  text(amt, width / 2, height / 2);
}

function keyPressed() {
  amt++;
  storeItem("amt", amt);
}

It works fine, but I’m having an issue on Chromebook specifically, where after I shut my Chromebook, the localStorage data resets. I’m running on Chromebook Gemini Lake, with the newest ChromeOS version.

model is not updated after manual change attribute value ckeditor 5

I trying use editor with custom tags
enter image description here
this tags has attributes. When I change value in html model dont know about it.
enter image description here
After change attribute value I havent any fire event.

Additionally
Attribute changing in external component angular, but html changed inside editor.

I tired several variants with attributeToAttribute but not result.
Any ideas, please.