Error: Parse Error – Invalid header value char in Node.js

I’m encountering a “Parse Error: Invalid header value char” in my Node.js application. The error stack trace points to an issue in the TLSSocket.socketOnData function. I’ve checked my code, but I’m unable to pinpoint the cause. Here’s a brief overview of my setup:

  • Using Express.js
  • MongoDB connection with Mongoose

The error occurs intermittently, and I suspect it might be related to the payload or headers. I’ve already tried the axios instance but it also same on Postman.

Any insights or suggestions on how to troubleshoot and resolve this issue would be greatly appreciated.

Error: Parse Error: Invalid header value charn    at TLSSocket.socketOnData (node:_http_client:534:22)n    at TLSSocket.emit (node:events:513:28)n    at addChunk (node:internal/streams/readable:315:12)n    at readableAddChunk (node:internal/streams/readable:289:9)n    at TLSSocket.Readable.push (node:internal/streams/readable:228:10)n    at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)

Why the chat-gpt cannot calculate the correct result of the rcursion of a closure function in a currying using Javascript?

There has a problem between chat-gpt and me. That is, I instruct the chat-gpt to calculate the output of the following javascript code, the correct answer of the this code is 243 but chat-gpt says me the actual answer if 60. Somome can explain the actual fact fro why chat-gpt can’t produce the correct answer. Code is following :

const h = (a) => {
  const g = (b) => {
    if (b <= 1) {
      return a;
    } else {
      return a * g(b - 1);
    }
  };
  return g;
};

const f = (a) => h(a);
const c = f(3);
console.log(c(5));

I tried to trace the control-flow of the code. I expect for the actual control flow of this code. I thinks there has some issue in this code not formally.

Calculate rolling incremental of properties from an array of objects

I have an array of objects of this structure

- day
- dimension
- sub-dimension
  ...
- sub-sub-dimension
- measure1, measure2,...

and want to convert into this structure to feed into a dashboard template, with the “diff” is DoD difference.

- day
- dimension
- sub-dimension
  ...
- sub-sub-dimension
- measure1: [value,#diff,%diff]
- measure2: [value,#diff,%diff]
  ...

My best logic so far is

  • Loop through the data and group by every value combinations of dimensionList.
  • Popular the an array for each measure of each combination measureList with all days.
  • Calculate rolling difference for each measure.
  • Update back to the original data.

My best attemp failed at the first step at generating the array for each combinations and my logic isn’t neat as well. Hope someone could help, it’s okay to use packages.

    const dimensionList = ["city","category"];
    const measureList = ["order","buyer","gmv"];
    const newData = [];
    measureList.forEach(measure => {
      newData.push(
        {
          measure: measure,
          values: _.chain(data)
                   .groupBy(data,item => dimensionList.map(dim => item[dim]).join('-'))
                   .mapValues(group => _.map(group, measure))
                   .value()
        }
      )
    });

Example data and the expected results

[
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "X",
        "order": 100,
        "buyer": 150,
        "gmv": 1000
    },
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "Y",
        "order": 110,
        "buyer": 160,
        "gmv": 1200
    },
    {
        "day": "2024-01-02",
        "city": "A",
        "category": "X",
        "order": 120,
        "buyer": 170,
        "gmv": 1400
    },
    ...
]
[
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "X",
        "order": [100,null,null]
        "buyer": [50,null,null]
        "gmv": [1000,null,null]
    },
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "Y",
        "order": [110,null,null]
        "buyer": [160,null,null]
        "gmv": [1200,null,null]
    },
    {
        "day": "2024-01-02",
        "city": "A",
        "category": "X",
        "order": [125,25,0.25]
        "buyer": [60,10,0.2]
        "gmv": [1400,400,0.4]
    },
    ...
]

how to pass html element through a javascript function as parameter

I fall in trouble to pass a html element to a javascript function.

The div what I try to delete and pass to the function, that contains two things, one is <input> element and another one is <p> element.

In this case, I am try to make a todo list, where I am trying to delete something, and it should delete from there, then appeared on other div. So, I pass the nodelist(denoted as node over here) to show_*delete_*items(node[i]), I thought it will be appeared in that div, but its not happening, whats wrong here, can anybody help me to elevate my wrong approach.

function delete_items() {
    console.log('delete items function got called!');

    let node = document.getElementsByClassName('check_box_div');
    console.log(node);
    // node
    // let n_0 = node[0].childNodes;
    // console.log(n_0[0].checked);
    // console.log(node[0].childNodes);

    for (let i = 0; i < node.length; i++) {
        let ch = node[i].childNodes;
        if (ch[0].checked === true) {
            console.log('This is true and removed!', i);
            // ch.
            console.log('parent element = ', ch.parentElement);
            console.log('node = ', node[i]);
            show_delete_items(node[i]);  //I try to pass this nodelist 
            /*
            when I print that node, it looks like this:    
            <div class="check_box_div" style="padding: 10px 15px; border-top: 1px solid black; border-bottom: 1px solid black; margin: 10px; display: flex; flex-direction: row; justify-content: space-between;"><input type="checkbox"><p class="para"> vbcfb </p></div>
*/

            ch[0].parentElement.remove();
        }
    }
}

function show_delete_items(it) {
    
    if (document.getElementsByClassName('del_div').length === 0) {


        let del_div = document.createElement('div');
        del_div.className = 'del_div';
        del_div.style.backgroundColor = 'green';
        del_div.style.width = '400px';
        del_div.style.height = 'auto';
        del_div.style.margin = 'auto';

        let main_container = document.body;
        main_container.appendChild(del_div);
    }
    let new_div = document.createElement('div');
    new_div.className = 'inner_div';
   
    new_div.appendChild(it.childNodes);
    // new_div.insertAdjacentHTML(it);

    let del_div_check = document.querySelector('.del_div');
    del_div_check.appendChild(new_div);

}

Uncaught TypeError: Failed to execute ‘appendChild’ on ‘Node’: parameter 1 is not of type ‘Node’.

Showing this error message, when I try above code.

from show_delete_item function:

I tried

  1. new_div.append(it)

  2. let len = it.length;
        for (let i = 0; i < len; i++) {
            const element = it[i];
            console.log(i,' = ', element.value);
            new_div.appendChild(element);
        } //But this was not working
    
  3. new_div.appendChild(it[0]);
    new_div.appendChild(it[1]); //Error message showed : Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    
  4. new_div.insertAdjacentHTML(it);
    

Cors error in react (vite) when call API (dot net web API)

When I want to call Post API (dot net 4 web API) with fetch in React (Vite), the below error occured

Access to fetch at ‘API URL’ from origin ‘http://localhost:5173’ has
been blocked by CORS policy: Response to preflight request doesn’t
pass access control check: It does not have HTTP ok status.

The API accept request from any origin. (Access-Control-Allow-Origin=*)

The code that I use is:

fetch(CURL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
            'Access-Control-Allow-Origin': '*',
            "Access-Control-Allow-Headers": 'Content-Type',
            "Access-Control-Allow-Methods": 'GET,PUT,POST,DELETE'
        },
        body: JSON.stringify(RequestData)
    })
...

can we Capture onchange Event for Dynamic TextAreas Without Defining Class in CSS?

I have a requirement where I need to capture the onchange event of a textarea. The challenge is that the textarea is dynamic, and its number can vary based on user input (e.g., single or multiple textareas).

Here is an example of how the HTML looks:

<textarea name="userInput1" id="userInput1" rows="4" cols="50" class="textareaClass"></textarea>
<textarea name="userInput2" id="userInput2" rows="4" cols="50" class="textareaClass"></textarea>
<textarea name="userInput3" id="userInput3" rows="4" cols="50" class="textareaClass"></textarea>
<!-- ... -->
<textarea name="userInputN" id="userInputN" rows="4" cols="50" class="textareaClass"></textarea>

And the jQuery code I’m using to capture the onchange event:

$(document).ready(function() {
    $(".textareaClass").on("change", function() {
        var textareaValue = $(this).val();
        // My logic
    });
});

My question is: Can I use the class attribute “textareaClass” without defining the class in the CSS? Is this considered standard practice, or is there a better way to capture the onchange event for dynamically generated textareas?

I appreciate any insights or alternative approaches to achieve this. Thank you!

9.999501.toFixed(3) = ‘10.000’ but 9.9995000000000001.toFixed(3) = ‘9.999’ [duplicate]

> 9.9995.toFixed(3)
'9.999'
> 9.999501.toFixed(3)
'10.000'
> 9.9995000001.toFixed(3)
'10.000'
> 9.9995000000001.toFixed(3)
'10.000'
> 9.9995000000000001.toFixed(3)
'9.999'

I’ve been writing a simple function to render a percentage into 6 string characters for generating aligned output. Once I did some testing focused on rounding I ran into this weird rounding behavior. Anyone know what’s going on?

It seems likely that 9.9995000000000001 is too many digits and evaluates identically to 9.9995, but it still begs the question of why the rounding threshold is not met by 9.9995

Manipulating text assessment

i have a question about assessment for manipulating text. I have to make the song titles lower case and a song without an apostrophie and then do a search to see if the search is successful which it is. So why the error when I click run test?

I entered this:

let setSongTitle = "Seen a Thousand Things";
setSongTitle = setSongTitle.toLowerCase();
console.log(setSongTitle);

setSongTitle = "We're all light";
setSongTitle = setSongTitle.toLowerCase().replace(/'/g, "");
console.log(setSongTitle);

The song title, “Seen a Thousand Things”, should be all lower case and the song, “We’re all light”, should be, “were all light”.

Typescript form data not being passed to next.js api POST request [duplicate]

The issue at hand is that im attempting to take three form fields from the client side and email those details via amazons SES using Next.js however the email is sent, but the fields are undefined i do not recieve an internal server error or any error of anykind for that matter. ive tried to use express but i am very unfamiliar with it and had trouble finding a solution using that method. Im assuming the issue is to do with how i am recieving the form data via the next request however im fairly new to next js and have been doing this on a whim. ive tried changing between NextRequest and NextApiRequest as well and it has yielded the same result, here is my minimal reproducible, i am interested in how to fix this but im more interested in how to properly work with next api requests and if some insight could be provided it would help greatly!

Client:

'use client'

import { useState } from 'react';

export default function Newsletter() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    message: '',
  });

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    try {
      console.log(formData)
      const response = await fetch('/api/sendEmail', {
        method: 'POST',
        body: JSON.stringify(formData),
      });
      console.log(response)
    } catch (error) {
      console.log(error)
    }
  };

  return (
    <section>
            <form className="w-full lg:w-1/2" onSubmit={handleSubmit}>
              <div className="">
                <input name="email" type="email" className="" placeholder="Your best email…" aria-label="Your best email…" onChange={handleInputChange} />
              </div>
              <div className="">
                <input name="name" type="name" className="" placeholder="First and Last Name" aria-label="First and Last Name" onChange={handleInputChange}/>
              </div>
              <div className="">
                <textarea name="message" className="" placeholder="Details *Optional" aria-label="Details" onChange={handleInputChange}/>  
              </div>
              <button type="submit" className="">Contact</button>
            </form>

          </div>

        </div>

      </div>
    </section>
  )
}

Server:

import type { NextApiRequest, NextApiResponse } from 'next';
import { SES } from '@aws-sdk/client-ses';

export async function POST(req: NextApiRequest, res: NextApiResponse) {
  const {name, email, message} = req.body
  
  try {
    const ses = new SES({

      credentials: {
        accessKeyId: 'some-key',
        secretAccessKey: 'some-secret-key',
      },

      // e.g., 'us-east-1'
      region: 'us-east-1',
    });

    const params = {
      Destination: {
        ToAddresses: ['[email protected]', '[email protected]'],
      },
      Message: {
        Body: {
          Text: { Data: `Name: ${name}nnEmail: ${email}nnMessage: ${message}` },
        },
        Subject: { Data: 'New Contact Form Submission!' },
      },
      Source: '[email protected]', // Must be verified in SES
    };

    await ses.sendEmail(params);
    console.log('Email sent successfully');
    return Response.json("temp")
  } catch (error) {
    console.error(error);
    console.log('Failed to send email' );
    return Response.json('temp')
  }
}

ive created this based off of the docs at: https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations and my knowledge of react however im new to both typscript and next, usually my preferred frameworks are react and django.

Plaid link-initialize.js shows loading symbol forever

I’m trying to use the Plaid development environment to test out the plaid API. I am creating a command line cli for plaid so I currently don’t have a need for a server, so currently I generate a link token with Go and render the token into an HTML blob. When I open that HTML file in my browser and click the “Link account” button it hangs indefinitely.

Here is the go code generating the link and rendering into the HTML:

package main

import (
    "context"
    _ "embed"
    "html/template"
    "log"
    "os"
    "time"

    "github.com/plaid/plaid-go/plaid"
    "github.com/vrischmann/envconfig"
)

type config struct {
    PlaidApi struct {
        ClientId string `envconfig:"PLAID_CLIENT_ID"`
        Secret   string `envconfig:"PLAID_SECRET"`
    }
}

//go:embed token.html.tmpl
var tokenPage string

func main() {
    cfg := config{}

    if err := envconfig.Init(&cfg); err != nil {
        log.Fatalf("failed to load config from environment: %s", err)
    }

    ctx := context.TODO()
    plaidCfg := plaid.NewConfiguration()
    plaidCfg.UseEnvironment(plaid.Development)
    cli := plaid.NewAPIClient(plaidCfg)
    phoneNumber := "+1 888 888-8888"
    user := plaid.LinkTokenCreateRequestUser{
        ClientUserId: "1",
        PhoneNumber:  &phoneNumber,
    }
    request := plaid.NewLinkTokenCreateRequest(
        "Personal Finance App",
        "en",
        []plaid.CountryCode{plaid.COUNTRYCODE_US},
        user,
    )
    request.SetProducts([]plaid.Products{plaid.PRODUCTS_TRANSACTIONS})
    request.SetSecret(cfg.PlaidApi.Secret)
    request.SetClientId(cfg.PlaidApi.ClientId)
    linkTokenCreateResp, _, err := cli.PlaidApi.LinkTokenCreate(ctx).LinkTokenCreateRequest(*request).Execute()
    if err != nil {
        if pErr, err := plaid.ToPlaidError(err); err == nil {
            log.Printf("Error from plaid: %s", pErr.ErrorMessage)
        }
        log.Fatalf("failed to get link request: %s", err.Error())
    }
    log.Printf("link token: %s", linkTokenCreateResp.GetLinkToken())

    tmplate, err := template.New("token.html").Parse(tokenPage)
    if err != nil {
        log.Printf("Html tmplate:n%s", tokenPage)
        log.Fatalf("Failed to create HTML template: %s", err)
    }

    page, err := os.CreateTemp("", "catnip_*.html")
    if err != nil {
        log.Fatalf("Failed to create temp file: %s", err)
    }
    defer os.Remove(page.Name())
    data := struct {
        LinkToken string
    }{LinkToken: linkTokenCreateResp.LinkToken}
    if err := tmplate.Execute(page, data); err != nil {
        log.Printf("template data: %#v", data)
        log.Printf("html template:n%#v", tokenPage)
        log.Fatalf("Failed to render token page: %s", err)
    }

    log.Printf("token page path:n%s", page.Name())
    time.Sleep(2 * time.Minute)
}

This is the template (token.html.tmpl):

<button id="link-button">Link Account</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<script type="text/javascript">
(async function($) {
  var handler = Plaid.create({
    // Create a new link_token to initialize Link
    token: "{{ .LinkToken }}",
    onLoad: function() {
        console.log("link token: '{{ .LinkToken }}")
    },
    onSuccess: function(public_token, metadata) {
        console.log("Success!");
    },
    onExit: function(err, metadata) {
      if (err != null) {
          console.log(err);
      }
    },
    onEvent: function(eventName, metadata) {}
  });

  $('#link-button').on('click', function(e) {
    handler.open();
  });
})(jQuery);
</script>
  • Looked in the console, I didn’t see any errors
  • Looked at the network traffic, oddly clicking the button doesn’t seem to create any traffic

HTML5 Viewport video replays on scroll

I have a video on my website that I set to play/pause on viewport. Once the video ends it is in the paused state, however, as soon as I scroll, it begins to replay. What would be the correct way to keep the video from replaying and remaining in the paused state, until the user presses the play button?

Here is the code I am using for Viewport:

(function($) {

  $(document).ready(function() { 
  
    var $win = $(window);
    
    var elementTop, elementBottom, viewportTop, viewportBottom;

    function isScrolledIntoView(elem) {
      elementTop = $(elem).offset().top;
      elementBottom = elementTop + $(elem).outerHeight();
      viewportTop = $win.scrollTop();
      viewportBottom = viewportTop + $win.height();
      return (elementBottom > viewportTop && elementTop < viewportBottom);
    }
        
    if($('video').length){

      var loadVideo;

      $('video').each(function(){
        $(this).attr('webkit-playsinline', '');
        $(this).attr('playsinline', '');

        $(this).attr('id','loadvideo');
        loadVideo = document.getElementById('loadvideo');
        loadVideo.load();
      });

      $win.scroll(function () { // video to play when is on viewport 
      
        $('video').each(function(){
          if (isScrolledIntoView(this) == true) {
              $(this)[0].play();
          } else {
              $(this)[0].pause();
          }
        });
      
      });  // video to play when is on viewport

    } // end .field--name-field-video
    
    
   });
  
})(jQuery);

I’ve tried to play with this code, but could not get it to work..

<script>
    var videoList = [];
    var scrollPauseList = [];
    var clickedPauseList = [];
</script>
<script>    
    var myScrollFunc = function() {

        $(".video-js").each(function(){ 

            var inView = $(this).is(":in-viewport");
            var isPaused = $(this)[0].player.paused();
            var playerIdx = videoList.indexOf(this.id);
            var scrollPaused = scrollPauseList[playerIdx];
            var clickPaused = clickedPauseList[playerIdx];

            if (inView) {                       
                var hasEnded = $(this)[0].player.ended();
                var curTime = $(this)[0].player.currentTime();
                var hasStarted = curTime > 0;
                if(hasStarted && !hasEnded && !clickPaused)
                {
                    scrollPauseList[playerIdx] = false;
                    $(this)[0].player.play();
                }
            } else if(!isPaused) {                      
                scrollPauseList[playerIdx] = true;
                $(this)[0].player.pause();
            }
        });
    };      

    $(window).scroll(myScrollFunc);     
</script>   

<video  
  class="video-js" controls></video>

<script>
$(".video-js").each(function(){ 
        videoList[videoList.length] = this.id;
        scrollPauseList[scrollPauseList.length] = false;
        clickedPauseList[scrollPauseList.length] = false;
    }); 

for(var i = 0; i < videoList.length; i++)
{
    var playerID = videoList[i];
    var player = videojs(playerID);

    player.on('pause', function() {
        var pID = videoList.indexOf(this.id());

        if(!scrollPauseList[pID])
        {
            clickedPauseList[pID] = true;
            scrollPauseList[pID] = false;
        }
        else
        {
            clickedPauseList[pID] = false;
            scrollPauseList[pID] = false;
        }
    });
}       
</script>

How would I create a Block Editor in HTML, CSS,JS [closed]

I tried about 4 times and every single time the code broke. I’m trying to make a Block Editor like Scratch for CCS. I want to add drag and drop functionality, that worked.

Then I went to add the functionality to nest blocks in events/if statements but then it wouldn’t nest out. I added duplicate/delete functionality.

May I know how to add drag and drop with nesting and unnesting (without react or anything else just plain html, css, js) ?