Sending multiple files from axios to nestjs (Multipart: Boundary not found)

I’m attempting to send multiple files in a multipart/form-data. This form will have one required file imagem and on required data which will be a json. I has a optional anexos which is an array of images. I’m gettings an error when attempting to send only an image from axios to my nestjs backed.

From the app side I receive:

{"error": "Bad Request", "message": "Multipart: Boundary not found", "statusCode": 400}

If I remove multipart/form-data, I get an error in nestjs:

[Nest] 29165  - 01/21/2025, 10:34:06 AM   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'imagem')
TypeError: Cannot read properties of undefined (reading 'imagem')
    at ReceitasController.create

React Native axios logic:

static async create(file: any, receita: Receita): Promise<Receita> {
    const formData = new FormData()

    formData.append('imagem', {
      type: file.mime,
      name: file.fileName,
      uri:
        Platform.OS === 'android' ? file.uri : file.uri.replace('file://', ''),
    })

    formData.append('data', JSON.stringify(receita))

    return http.post('/receitas', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
  }

Nest.js:

@Post()
@UseInterceptors(
  FileFieldsInterceptor([
    { name: 'imagem', maxCount: 1 },
    { name: 'anexos', maxCount: 5 },
  ]),
)
async create(
  @UploadedFiles()
  files: { imagem: Express.Multer.File[]; anexos?: Express.Multer.File[] },
  @Body() body: { data: string },
  @CurrentUser() user: TokenPayload,
) {
  const file = files.imagem[0]

  const b = JSON.parse(body.data)

  const rc = createReceitaSchema.parse(b)

  return await this.receitasService.create(
    file,
    rc,
    user.sub,
    files.anexos,
  )
}

The http is:

const http = axios.create({
  baseURL: 'http://192.168.1.45:3333/',
  withCredentials: true,
}) as APIInstaceProps

This works fine on my postman:

enter image description here

Android WebView – Origin Private File System – An attempt was made to break through the security policy of the user agent

We have an Android app using WebView to display part of the user interface. In app telemetry we see that on some user device the following exception is thrown:

SecurityError: Failed to execute ‘getFileHandle’ on
‘FileSystemDirectoryHandle’: An attempt was made to break through the
security policy of the user agent.

Here is the code causing the exception:

const root = await navigator.storage.getDirectory();
const fileHandle = await root.getFileHandle(name, {create: true});

I would expect the exception to be thrown in a browser with strict privacy controls. However, the problem appears in a WebView component. What’s more puzzling the problem appears only on some devices. For example, I’m not able to reproduce the problem on any of our test smartphones.

The OPFS API is being used in a secure context (HTTPS page).

Most often the exception is thrown in WebView version 132, running on Android 14.

What may cause the WebView to limit origin private file system API use?

Oracle APEX dynamically set item value on a datepicker

I am working on an Oracle APEX application where I need to dynamically format a user’s input in a Date Picker item. The desired behavior is:

When the user types 20022025 (for example), the item should automatically reformat it to 20.02.2025 (i.e., DD.MM.YYYY) upon losing focus.
If a date is selected using the date picker, the value should remain unchanged.
The format mask for the Date Picker is already set to DD.MM.YYYY.

What I have tried:

//PL/SQL Dynamic Action
declare
begin
  SELECT TO_CHAR(TO_DATE(:BIRTH_DATE, 'DDMMYYYY'), 'DD.MM.YYYY') 
    INTO :BIRTH_DATE
    FROM DUAL;
end;

//PL/SQL with Conditional Formatting
declare
  v_formatted_date varchar2(10);
begin
  if regexp_like(:BIRTH_DATE, '^d{8}$') then
    v_formatted_date := substr(:BIRTH_DATE, 1, 2) || '.' || 
                        substr(:BIRTH_DATE, 3, 2) || '.' || 
                        substr(:BIRTH_DATE, 5, 4);
  end if;
  :BIRTH_DATE:= v_formatted_date;
end;

//JavaScript Dynamic Action
var pid = $(this.triggeringElement).attr("id");
var value = apex.item(pid).getValue(); 
console.log("value:", value);

if (/^d{8}$/.test(value)) {
  var formattedValue = value.substring(0, 2) + '.' + 
                       value.substring(2, 4) + '.' + 
                       value.substring(4);
  console.log("Formatted value:", formattedValue);
  apex.item(pid).setValue(formattedValue);
}

//Set Value Action with PL/SQL Function Body
declare
begin
  IF REGEXP_LIKE(:BIRTH_DATE, '^d{8}$') THEN
    SELECT TO_CHAR(TO_DATE(:BIRTH_DATE, 'DDMMYYYY'), 'DD.MM.YYYY') 
      INTO :BIRTH_DATE
      FROM DUAL;
  end if;
end;

bug in chromium 132 when iterating over very large objects (1 million keys)

It seems there is a bug in chrome 132 with very large objects (1 million keys).

  • chrome 132.0.6834.84
  • V8 13.2.152.27

Firefox works fine

Here is a minimal repro.

  • For some reason, the first time chrome loads the page, there are only 2 errors.
  • After I refresh, there are 3 errors.
<html>
  <script>
    const count = 1e6; // 1e5 => OK, 1e6 => ERROR

    const big = {};
    for (let i = 0; i < count; i++) {
      big[`key_${i}`] = { a: i, b: i * 2, c: i * 3 };
    }

    console.log('begin');

    try {
      for (let k in big) {
        if (big[k] === undefined) {
          throw new Error();
        }
      }
    } catch (e) {
      console.log(`for (k in big) => ERROR with count = ${count}`);
    }

    try {
      const keys = Object.keys(big);
      for (let k of keys) {
        if (big[k] === undefined) {
          throw new Error();
        }
      }
    } catch (e) {
      console.log(`Object.keys(big) => ERROR with count = ${count}`);
    }

    
    try {
      const keys = Object.getOwnPropertyNames(big);
      for (let k of keys) {
        if (big[k] === undefined) {
          throw new Error();
        }
      }
    } catch (e) {
      console.log(`Object.getOwnPropertyNames(big) => ERROR with count = ${count}`);
    }

    console.log('done');
  </script>
</html>

Is there a way to proxy a streamed answer in AWS Lambda js?

I’m using loopback 4 as backend framework and I deploy my APIs on AWS lambda using Serverless framework (followed this guide: https://medium.com/@hitesh.gupta/running-loopback-v4-on-aws-lambda-56064a97b5c3). I want to make a Bedrock API and stream model response (as a GPT like) but I can’t manage to stream my response as it was stuck in buffering mode.

serverless.yml

functions:
  stream:
    handler: lambda.handler
    timeout: 60
    url:
      cors: true
      invokeMode: RESPONSE_STREAM
  app:
    handler: lambda.handler # reference the file and exported method
    events: # events trigger lambda functions
      - http: # this is an API Gateway HTTP event trigger
          path: /
          method: ANY
          cors: true
      - http: # all routes get proxied to the Express router
          path: /{proxy+}
          method: ANY
          cors: true

lambda.js

const awsServerlessExpress = require('aws-serverless-express');
const AWS = require('aws-sdk');
const application = require('./dist');
const app = new application.StudyApplication({
  rest: {
    openApiSpec: {
      setServersFromRequest: true,
    },
  },
});
const server = awsServerlessExpress.createServer(app.restServer.requestHandler);
exports.handler = async (event, context) => {
  console.log('Event: ', event);

  await app.boot();
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

my test controller:

import {inject} from '@loopback/core';
import {post, Response, RestBindings} from '@loopback/rest';
import {Readable} from 'stream';
// import {inject} from '@loopback/core';
export class PromptController {
  constructor() {}
  @post('/prompt', {
    responses: {
      '200': {
        description: 'Stream fixed text in chunks',
        content: {
          'text/event-stream': {},
        },
      },
    },
  })
  async streamFixedText(
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise<void> {
    response.set('Content-Type', 'text/event-stream');
    response.set('Connection', 'keep-alive');
    const chunks = [
      'This is the first chunk of the text.',
      ' Here comes the second chunk.',
      ' And finally, the last chunk.',
    ];

    const readable = new Readable({
      read() {
        let index = 0;

        const intervalId = setInterval(() => {
          if (index < chunks.length) {
            this.push(`data: ${chunks[index]}nn`);
            index++;
          } else {
            this.push(null);
            clearInterval(intervalId);
          }
        }, 1000);
      },
    });

    response.on('close', () => {
      readable.destroy();
    });

    readable.pipe(response);
  }
}

I don’t know if there is a way to make it works.

Thanks a lot for taking the time to read my issue.
ITZouzouille

tried using streamifyResponse lib but it seems that the event object when requesting a lambda url isn’t the same as when we pass through API Gateway.

How to implement illustrator’s ability to identify closed paths with svg

I am making a website that helps making kufi typography art. Kufi is basically based on grids. it varies by the way the grid is constructed.

regular square grid circular grid

before, I used to make these grids using python’s turtle library. but now I will make it 100% frontend which means i need to handle the graphics using SVG and javascript.
the drawing itself isn’t the problem. the problem is that the drawing isn’t based on paths. it’s based on circles, rectangles and lines.
I need to be able to identify each closed region like illustrator’s live paint bucket does.
illustrator’s live paint bucket
so that it basically looks like pixel art apps where you can hover your mouse on any closed region and it detects it and can color it individually.
A sample of the grids written in svg:

<svg width="1000" height="1000"><circle r="300" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="290" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="270" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="260" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="240" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="230" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="210" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="200" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="180" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="170" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="150" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="140" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="120" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="110" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="90" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="80" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="60" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="50" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="30" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><circle r="20" cx="500" cy="500" fill="none" stroke="black" stroke-width="0.5"></circle><rect x="495" y="200" width="10" height="600" transform="rotate(0, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(18, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(36, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(54, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(72, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(90, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(108, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(126, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(144, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect><rect x="495" y="200" width="10" height="600" transform="rotate(162, 500, 500)" fill="none" stroke="black" stroke-width="0.5"></rect></svg>

I tried to use intersections libraries, but I couldn’t find a way to know which intersection is which. or how to make separate paths of each closed region

The modification of the browser’s mouse cursor style becomes invalid after the browser loses focus

I have a requirement to change the browser’s mouse cursor style dynamically to achieve a mouse animation effect. To simplify the content for discussion, it can be represented by the following code:

const cursorTypes = ["default", "pointer", "text", "move", "help", "progress", "crosshair", "not-allowed", "zoom-in", "zoom-out", "grab", "grabbing"];
let cIndex = 0;

setInterval(() => {
  console.log(cIndex);
  document.body.style.cursor = cursorTypes[cIndex];
  cIndex++;
  if (cIndex >= cursorTypes.length) {
    cIndex = 0;
  }
}, 500);

The problem is that when the browser loses focus, although the setInterval function continues to run normally, the mouse cursor style does not change. However, when the mouse is continuously moved within the browser viewport, the styles that are not rendered will be applied sequentially at the set interval. Once the mouse stops moving, the rendering stops immediately until the browser regains focus. Why is this happening? I suspect this might be related to the browser’s rendering buffer.

I have tried using requestAnimationFrame function for animation updates:

let frameIndex = 0;
let step = (timestamp, elapsed) => {
  if (elapsed > 1000 / frameRate) { 
    document.body.style.cursor = cursorTypes[cIndex]; 
    frameIndex++;
    if (frameIndex >= frameURLs.length) {
      frameIndex = 0;
    }
    elapsed = 0;
  }
  console.log(frameIndex);
  window.requestAnimationFrame((_timestamp) =>
    step(_timestamp, elapsed + _timestamp - timestamp)
  );
};
window.requestAnimationFrame((timestamp) => step(timestamp, 0));

Or using the CSS animation property:

@keyframes cursor-animation-keyframes{
  0% { cursor: default; } 
  6% { cursor: pointer; } 
  ... 
}

.cursor-animation { 
  animation: cursor-animation-keyframes 1866ms step-end infinite; 
}

But the results are the same with no difference.
What should I do to ensure that the mouse cursor style modification still works after the browser loses focus?

Url, not updating with useSearchParams and select tag option is not working while sorting out data

The issues are the select tag option which is not working after I used useSearchParams to update URL by sorting data, the URL is not showing the option when I select the options. The expectation is that when I select any option, the URL should be updating with the option but otherwise.

This is the select tag option code which I created as a reusable component so that I can

const Select = ({ options, value, onChange, ...props }) => {
  return (
    <StyledSelect value={value} {...props}>
      {options.map((option, index) => (
        <option value={option.value} key={index} onChange={onChange}>
          {option.label}
        </option>
      ))}
    </StyledSelect>
  );
};

export default Select;

reuse it another component.

Then the next work is where I called the above component inside the Sort component which contain the logic for the updating the URL and sorting of the array of object(options):

import { useSearchParams } from 'react-router-dom';
import Select from './Select';

const SortBy = ({ options }) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const sortBy = searchParams.get('sortBy') || '';

  function handleChange(e) {
    searchParams.set('sortBy', e.target.value);
    setSearchParams(searchParams);
  }

  return (
    <Select
      value={sortBy}
      options={options}
      type="white"
      onChange={handleChange}
    />
  );
};

export default SortBy;

This last code base is how the SortBy component is call and those options are pass into it

type here

How to add all child arrays to one array?

I have a constant file like that:

const files = [{
    id: 232141332,
    title: "Работа",
    type: "FOALDER",
    opened: true,
    level: 0,
    fatherId: null,
    children: [{
        id: 734573086,
        title: "MA5600",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
            id: 867407333,
            title: "удалить плату",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          },
          {
            id: 110345245,
            title: "добавить плату",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          }
        ]
      },
      {
        id: 222225454,
        title: "C300M",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
          id: 333334256,
          title: "добавить опцию TR-82",
          type: "FILE",
          opened: false,
          level: 2,
          fatherId: 222225454,
          children: []
        }]
      }
    ]
  },
  {
    id: 23232,
    title: "Прога",
    type: "FOALDER",
    opened: true,
    level: 0,
    fatherId: null,
    children: [{
        id: 2323242,
        title: "React",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 1224232,
        children: [{
            id: 45674734,
            title: "добавить компонент",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          },
          {
            id: 5368876,
            title: "удалить компонент",
            type: "FILE",
            opened: false,
            level: 2,
            fatherId: 734573086,
            children: []
          }
        ]
      },
      {
        id: 258089,
        title: "SQL",
        type: "FOALDER",
        opened: true,
        level: 1,
        fatherId: 232141332,
        children: [{
          id: 1112312,
          title: "посмотреть количество по условию",
          type: "FILE",
          opened: false,
          level: 2,
          fatherId: 222225454,
          children: []
        }]
      }
    ]
  }
]

How can I create an array which will be consist of al children of 1 element of files? Like this:

[{"MA5600"}, {удалить плату}, {добавить плату}, {C300M}, {добавить опцию TR-82}]. 

It is array of all children of object with title Работа, but I need not only names, full files.

How can I display more data(details) in the details popup of the TUI Calendar in Angular?

enter image description here

Title: “Unable to display more details in the TUI Calendar details popup in Angular”

Body:

I am working with the TUI Calendar in my Angular project. I have set up a calendar view, but I am facing an issue where the details page does not display additional data as expected. Although I have tried to configure the popup to show more details, only limited information appears, and the rest is missing.

Expected Results:

The details popup should display all relevant data, including additional information that I want to show when clicking on an event in the calendar.
Actual Results:

The details popup only displays a limited amount of data, and the additional details I want to show are not appearing.
Steps to Reproduce:

Set up TUI Calendar in Angular.
Configure the details popup to show more information.
Click on an event to open the details page.
Observe that only a subset of the data is displayed.

Using Flask, Jquery, when attempting to set src using attr() call only works some of the time

I have the following code in an HTML file, this is meant to both allow for text to appear and stay on screen, but also for the webpage to play audio, however the audio, around 75% of the time will replay previous audio instead of new audio after submit button is pressed for a second time.

$(document).ready(function(){
        $("#messageArea").on("submit", function(event){
          var rawText = $("#text").val();

          $("#text").val("");
          $("#messageForm").append(rawText + "   ||   ");

          $.ajax({
            cahce:false,
            data:{
              message:rawText,
            },
            type:"POST",
            url:"/getChat",
          }).done(function(data) {
            var botHTML = data
            $("#messageForm").append($.parseHTML(botHTML));
            $('<audio></audio').attr({
              'src':'audio/a1.mp3',
              'volume':0.4,
              'autoplay':'autoplay',
              'controls':'controls',
            });
            console.log("here")
          });

          event.preventDefault();
        });
      });

Here is the function that sends the audio

@app.route("/audio/<filename>")
def sendAudio(filename , methods=['GET', 'POST']):
    print("sending audio", filename)
    return send_file(f"audio/{filename}",mimetype="audio/mpeg")

as shown in the image audio is not called certain times, I believe it has to do with the ajax function, but I am out of ideas

I have tried to alter the caching, alter where it is placed, tried creating a separate ajax GET call, and tried using Flasks for_url function, but none of these have worked

Nodemon dont start the server.js

I recently started using Nodemon. But when I run this command “nodemon server.js”, comes this:

nodemon server.js
[nodemon] 3.1.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js tailwind.config.js`
[nodemon] clean exit - waiting for changes before restart

The problem is that Nodemon tries to start two files. How can I fix it? I have no nodemon.json file or similar. I installed Nodemon with npm install nodemon

Migrating from react-router-dom v5 to v6 structure

I have a similar structure as the one below in my project, currently using react-router-dom v5.

Let’s call this <Routes /> component:

<Switch>
  <Redirect from="/" to="/some/path" />
  <Redirect from="/main" to="/some/path" />
  <Route path="/main" component={SomePage} />
</Switch>

And inside <SomePage />, I render something like this:

return (
<>
 <Tabs />
 <Switch>
    <Route path="/some/path" component={MyComponent} />
    <Route path="/some/other" component={OtherComponent} />
    <Route path="/some/last" component={LastComponent} />
 </Switch>
</>
)

Now I am updating react-router-dom to v6, so I changed what was written in their docs…

In <Routes /> component:

<RouterRoutes>
 <Route path="/" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={<Navigate to="/some/path" />} />
 <Route path="/main" element={SomePage />} />
</RouterRoutes>

Did similar thing in <SomePage />, but now nothing is rendered and I don’t get what I need to change. I’ve looked on different threads around here on SO and Google and I still don’t get what is the recommended way to handle this whilst keeping project structure. I am trying to keep similar structure, as in <SomePage /> imports and creates its own routes and the main <Routes /> component is concerned only with the main routes.

Security issue: CacheStorage can violate Content Security Policy (CSP) rules

You know with this CSP configuration:

Content-Security-Policy: script-src 'self'

Then this code can’t be executed:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated= "console.log('HACKED!')"
eval(dangerousStringToBeEvaluated) // EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'

But if I know some JavaScript file is cached in CacheStorage (and is served by service-worker), then I can work around this limitation:

// Content-Security-Policy: script-src 'self'
const dangerousStringToBeEvaluated = "console.log('HACKED!')"
const cache = await caches.open('some-cache')
await cache.put(
  '/some-file.js',
  new Response(dangerousStringToBeEvaluated, {headers: {'Content-Type': 'application/javascript'}}),
)

And afterward, you see HACKED! in your console, when /some-file.js imported!


Is there any other CSP rule to prevent this behavior? For example, by limiting write-access to CacheStorage?

Form is Submitted right after the form is valid, but I haven’t touched the submit button

I use react-hook-form, yup validation.
If I finish the form, before I try to submit, the code automatically submits the form.
But I should prevent this before the user touches the submit button.
Any idea for the auto submission?

const Parent = () => {
  const schema = Yup.object().shape({
  .....
  });

const methods = useForm({
  defaultValues: {...},
  resolver: yupResolver(schema),
  mode: 'all',
});
....
}

And here is the child form

const Form = () => {
  const {handleSubmit, formState } = useFormContext();
  const onFinish = async (data: {[key: string]: any}) => {
  // submit
  }

return (
  <form onSubmit={handleSubmit(onFinish)}>
  ....
  </form>
)
}