Live stream a react component

Is it possible to live stream (youtube) a specific react component? I have some financial charts using web sockets that I would like to put on a live youtube channel, but not sure where to start.

I can only find documentation and packages around youtube to react, rather than the other way around.


I know that I could make my webcam stream my desktop and broadcast live that way, but I still need to use my computer and don’t want to show mouse movements, different tabs etc.

Thanks

TCP Communications on Browser

I am porting an Electron app for use in a static browser page (basically an html file and will be ran using the file:// protocol).

This Electron app is communicating with another app through TCP (127.0.0.1:port). For NodeJS, I am using the net module and it works perfectly fine.

But then, net module is not accessible in the browser and I can’t seem to find a module that supports TCP protocol on the browser (I’ve read that there is chrome tcp sockets, but it is already deprecated). Then there is also new technologies such as WebTransport but it feels like it is still in its very early stages and it seems to be using the http protocol somehow.

Instead, I tried using the native browser API for WebSockets (client-side). A pre-requisite for this is I need to run a server, so I used wc to create a server on the node side.

Now, my problem is, how can the external app (desktop app built using python) communicate with my server using TCP?

Another option I think I have is just create a local server using express and Axios and then still retain the TCP connectivity on the server side. I will use REST API to communicate between server-client.

But is there any other way to do this? Any other modules/technologies that allow using TCP on the browser?

Is it possible to implement this in React?

https://codepen.io/quill/pen/qNJMYB

I’m trying to implement this codepen in React Typescript but I’m getting so many bugs to the extent where if I post the code here, I think it’ll actually set people 10 steps back.

How do I go about re-implementing this in React from the start? I would put a bounty but i don’t have enough :/

this is the last stable version of my code

import React, { useRef, useEffect } from 'react';
import Quill, { RangeStatic } from 'quill';
import 'quill/dist/quill.snow.css';

interface Props {
  content: string;
  onChange: (value: string) => void;
}

const Editor2: React.FC<Props> = ({ content, onChange }) => {
    const editorRef = useRef<HTMLDivElement>(null);
    const toolbarRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (editorRef.current) {
            const editor = new Quill(editorRef.current, {
                theme: 'snow',
                modules: {
                    
                    toolbar: [
                        ["bold", "italic", "underline", "strike"],
                        ["blockquote", "code-block"],
                        [{ header: 1 }, { header: 2 }],
                        [{ list: "ordered" }, { list: "bullet" }],
                        [{ script: "sub" }, { script: "super" }],
                        [{ indent: "-1" }, { indent: "+1" }],
                        [{ direction: "rtl" }],
                        [{ size: ["small", false, "large", "huge"] }],
                        [{ header: [1, 2, 3, 4, 5, 6, false] }],
                        [{ color: [] }, { background: [] }],
                        [{ align: [] }],
                        ["clean"],
                    ],
                },
            });

            editor.on('text-change', () => {
                onChange(editor.root.innerHTML);
            });

            editor.root.style.backgroundColor = 'black';

            editor.root.addEventListener('mouseup', () => {
                const selection = editor.getSelection() as RangeStatic;
                if (selection && selection.length > 0) {
                    toolbarRef.current?.classList.add('show-toolbar');
                    // toolbarRef.current &&  toolbarRef.current?.style.top = `${selection.y + selection.height}px`;
                    // toolbarRef.current && toolbarRef.current.style.left = `${selection.x + selection.width / 2}px`;
                } else {
                    toolbarRef.current?.classList.remove('show-toolbar');
                }
            });

            editor.root.addEventListener('keydown', () => {
                toolbarRef.current?.classList.remove('show-toolbar');
            });

            editor.setContents(editor.clipboard.convert(content), 'silent');
        }
    }, []);

    const handleLink = () => {
        const url = window.prompt('Enter the URL');
        if (url) {
            const selection = (window as any).quill.getSelection() as RangeStatic;
            if (selection) {
                (window as any).quill.format('link', url);
            }
        }
    };

    return (
        <div>
            <div ref={toolbarRef} className="editor-toolbar">
                <button onClick={handleLink}>Link</button>
            </div>
            <div ref={editorRef} />
        </div>
    );
};

export default Editor2;

I’m a bit lost on how to implement the classes/blots.

Why .includes on string doesn’t detect lower case letters?

I wrote this to detect if the url contain this particular keyword i.e. recordId but if url contains it in lower i.e. recordid then it doesn’t detect.

How do I make them detect both because data can have both recordid or recordId.

if(url && url.includes("recordId") && url.includes("rt")){
      this._geRecordId(url);
    } 

 private async geRecordId(url){
    const linkedId = this._getURLValue('recordId' , url);
    if(!linkedId){
      return;
    }

private _getURLValue( name, url ) {
    if (!url) url = location.href;
    name = name.replace(/[[]/,"\[").replace(/[]]/,"\]");
    var regexS = "[\;]"+name+"=([^;]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( url );
    return results == null ? null : results[1];
 }

I tried changing regex

ImageData is different when getting one pixel

I am making a 2d light ray simulator with html canvas and i was creating a 1 pixel ImageData every time a ray moved so when i made it so it only created one at the start, it stopped working normally. The top is the old version that works and the bottom is the new version that doesn’t work. I expect it to do the same thing but in the new version the collisions are messed up.

const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext("2d");
        var mouseX = 0;
        var mouseY = 0;

        canvas.width = innerWidth;
        canvas.height = innerHeight;

        ctx.fillStyle = "rgb(10, 10, 10)";
        ctx.strokeStyle = "rgba(255, 255, 0)";
        ctx.lineWidth = 3;

        ImageData.prototype.getPixel = function(x, y, offset) {
            return this.data[(y * this.width + x) * 4 + offset];
        };
        
        function drawLine(first, second) {
            ctx.beginPath();
            ctx.moveTo(first[0], first[1]);
            ctx.lineTo(second[0], second[1]);
            ctx.stroke();
        };
        function mousemove(e) {
            mouseX = e.clientX;
            mouseY = e.clientY;
        };
        function drawScene() {
            ctx.fillStyle = "rgba(50, 50, 50, 1)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "rgba(10, 10, 10, 1)";

            ctx.fillRect(0, canvas.height-10, 200, 10);
            ctx.fillRect(0, canvas.height-210, 10, 200);
            ctx.fillRect(10, canvas.height-210, 200, 10);
            ctx.fillRect(200, canvas.height-190, 10, canvas.height-190);
        };
        drawScene();
        function render() {
            drawScene();
            let rays = [];
            var data;
            for (let angle = 0; angle < 360; angle += 3) { // for every ray
                let xv = Math.sin(angle*(Math.PI/180))*5;
                let yv = Math.cos(angle*(Math.PI/180))*5;
                let x = mouseX;
                let y = mouseY;
                let rayinitx = x;
                let rayinity = y;
                let collisions = 0;
                let opacity = 1;
                while (x > 0 && x < canvas.width && y > 0 && y < canvas.height) { // for every movement of every ray
                    x += xv;
                    data = ctx.getImageData(x, y, 1, 1);
                    let collide = false;
                    if (data.getPixel(0, 0, 0) === 10 && data.getPixel(0, 0, 1) === 10 && data.getPixel(0, 0, 2) === 10 && data.getPixel(0, 0, 3) === 255) {
                        xv *= -1;
                        x += xv;
                        collide = true;
                    };

                    y += yv;
                    data = ctx.getImageData(x, y, 1, 1);
                    if (data.getPixel(0, 0, 0) === 10 && data.getPixel(0, 0, 1) == 10 && data.getPixel(0, 0, 2) === 10 && data.getPixel(0, 0, 3) === 255) {
                        yv *= -1;
                        y += yv;
                        collide = true;
                    };
                    if (collide) {
                        rays.push([[rayinitx, rayinity], [x, y], opacity]);
                        opacity -= 1/5;
                        rayinitx = x;
                        rayinity = y;
                        if (opacity <= 0) {
                            break;
                        };
                    };
                };
                rays.push([[rayinitx, rayinity], [x, y], opacity]);
                rayinitx = x;
                rayinity = y;
            };
            rays.forEach(ray => {
                ctx.strokeStyle = `rgba(255, 255, 0, ${ray[2]})`;
                drawLine(ray[0], ray[1]);
            });
        };
        document.body.addEventListener("keypress", function(e){
            if (e.code == "Space") render();
        });
* {
                box-sizing: border-box;
            }
            html,body {
                width: 100%;
                height: 100%;
            }
            body {
                margin: 0;
                overflow: hidden;
            }
            canvas {
                width: 100vw;
                height: 100vh;
            }
<!DOCTYPE html>
<html lang="en">
    <body onmousemove="mousemove(event);">
        <canvas id="canvas"></canvas>
    </body>
</html>
const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext("2d");
        var mouseX = 0;
        var mouseY = 0;

        canvas.width = innerWidth;
        canvas.height = innerHeight;

        ctx.fillStyle = "rgb(10, 10, 10)";
        ctx.strokeStyle = "rgba(255, 255, 0)";
        ctx.lineWidth = 3;

        ImageData.prototype.getPixel = function(x, y, offset) {
            return this.data[(y * this.width + x) * 4 + offset];
        };
        
        function drawLine(first, second) {
            ctx.beginPath();
            ctx.moveTo(first[0], first[1]);
            ctx.lineTo(second[0], second[1]);
            ctx.stroke();
        };
        function mousemove(e) {
            mouseX = e.clientX;
            mouseY = e.clientY;
        };
        function drawScene() {
            ctx.fillStyle = "rgba(50, 50, 50, 1)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = "rgba(10, 10, 10, 1)";

            ctx.fillRect(0, canvas.height-10, 200, 10);
            ctx.fillRect(0, canvas.height-210, 10, 200);
            ctx.fillRect(10, canvas.height-210, 200, 10);
            ctx.fillRect(200, canvas.height-190, 10, canvas.height-190);
        };
        drawScene();
        function render() {
            drawScene();
            let rays = [];
            var data = ctx.getImageData(0, 0, canvas.width, canvas.height);
            for (let angle = 0; angle < 360; angle += 3) { // for every ray
                let xv = Math.sin(angle*(Math.PI/180))*5;
                let yv = Math.cos(angle*(Math.PI/180))*5;
                let x = mouseX;
                let y = mouseY;
                let rayinitx = x;
                let rayinity = y;
                let collisions = 0;
                let opacity = 1;
                while (x > 0 && x < canvas.width && y > 0 && y < canvas.height) { // for every movement of every ray
                    x += xv;
                    let collide = false;
                    if (data.getPixel(x, y, 0) === 10 && data.getPixel(x, y, 1) === 10 && data.getPixel(x, y, 2) === 10 && data.getPixel(x, y, 3) === 255) {
                        xv *= -1;
                        x += xv;
                        collide = true;
                    };

                    y += yv;
                    if (data.getPixel(x, y, 0) === 10 && data.getPixel(x, y, 1) == 10 && data.getPixel(x, y, 2) === 10 && data.getPixel(x, y, 3) === 255) {
                        yv *= -1;
                        y += yv;
                        collide = true;
                    };
                    if (collide) {
                        rays.push([[rayinitx, rayinity], [x, y], opacity]);
                        opacity -= 1/5;
                        rayinitx = x;
                        rayinity = y;
                        if (opacity <= 0) {
                            break;
                        };
                    };
                };
                rays.push([[rayinitx, rayinity], [x, y], opacity]);
                rayinitx = x;
                rayinity = y;
            };
            rays.forEach(ray => {
                ctx.strokeStyle = `rgba(255, 255, 0, ${ray[2]})`;
                drawLine(ray[0], ray[1]);
            });
        };
        document.body.addEventListener("keypress", function(e){
            if (e.code == "Space") render();
        });
* {
                box-sizing: border-box;
            }
            html,body {
                width: 100%;
                height: 100%;
            }
            body {
                margin: 0;
                overflow: hidden;
            }
            canvas {
                width: 100vw;
                height: 100vh;
            }
<!DOCTYPE html>
<html lang="en">
    <body onmousemove="mousemove(event);">
        <canvas id="canvas"></canvas>
    </body>
</html>

How to pass data from one component to store that in another component in react

I am new to react and building some pages. I have two separate index.tsx files under different folder but both folders have same parent folder.
I want to pass data from one index.tsx file after search button is clicked and save those values in another index.tsx.
These values are not drop down items and are not hardcoded in first index.tsx file. These are coming from API’s and whatever user selects from that dropdown I need to pass to another index.tsx.

I was looking for props but that all examples I saw were using HTML to send and receive the data and preview on screen but I don’t want to preview that instead of that I want to store those values in a variable in second index.tsx.

My code:

Note: This is not all of the code just a part of it. Also we have inbuild libraries to maintain standards so the syntax may differ from global syntax.

First index.tsx


import React, { useState, useEffect, useRef } from "react";

const Nemis3cOutboundConfig = () => {

const [statesApiResponse, setStatesApiResponse] = useState<StateModel[]>([]);
const [jsonViewResponse, setJsonViewResponse] = useState<JSON>();

const [outboundJson, setOutboundJson] = useState<JSON>();

const stateRef = useRef<HTMLDivElement>(null);
const [selectedState, setSelectedState] = useState<IDropdownItem>(undefined);
const [stateList, setStateList] = useState<IDropdownItem[]>([]);

const typeOfClaimRef = useRef<HTMLDivElement>(null);
const [selectedTypeOfClaim, setSelectedTypeOfClaim] = useState<IDropdownItem>(undefined);
const [typeOfClaimList, setTypeOfClaimList] = useState<IDropdownItem[]>([]);

const fileTypeIdRef = useRef<HTMLDivElement>(null);
const [selectedFileTypeId, setSelectedFileTypeId] = useState<IDropdownItem>(undefined);
const [fileTypeIdList, setFileTypeIdList] = useState<IDropdownItem[]>([]);


return (
       <>
        <LoadingIndicator
            loading={submitted}
            displayOverlay={true}
            size="l"
            loadingText={"Loading, Please Wait..."}
        >
            <Card
                header={
                    <H3Styles>
                        <h1>Outbound Config</h1>
                    </H3Styles>
                }>
                <hr />
                <form onSubmit={onSubmit}>
                    <div className="row">
                        <div ref={stateRef} className="col-3">
                            <FormControl
                                id="state"
                                error=""
                                required
                                className={"mt-m mb-m"}
                            >
                                <Label>State</Label>
                                <Dropdown
                                    type="single"
                                    items={stateList}
                                    value={selectedState}
                                    onChange={setSelectedState}
                                />
                            </FormControl>
                        </div>
                        <div ref={typeOfClaimRef} className="col-3">
                            <FormControl
                                id="type-of-claim"
                                error=""
                                required
                                className={"mt-m mb-m"}
                            >
                                <Label>Type of Claim</Label>
                                <Dropdown
                                    type="single"
                                    items={typeOfClaimList}
                                    value={selectedTypeOfClaim}
                                    onChange={setSelectedTypeOfClaim}
                                />
                            </FormControl>
                        </div>
                        <div ref={fileTypeIdRef} className="col-3">
                            <FormControl
                                id="file-type-id"
                                error=""
                                required
                                className={"mt-m mb-m"}
                            >
                                <Label>File Type ID:</Label>
                                <Dropdown
                                    type="single"
                                    items={fileTypeIdList}
                                    value={selectedFileTypeId}
                                    onChange={setSelectedFileTypeId}
                                />
                            </FormControl>
                        </div>
                        <div className="col-3 ${styles.sbmtBtn}">
                            <Button
                                onPress={onSubmit}
                                className={`mr-xs mt-s ${styles.sbmtBtn}`}
                            >
                                Search
                            </Button>
                        </div>
                    </div>
                </form>
            </Card>
            <br></br>
        </LoadingIndicator>
  }  
  export default Nemis3cOutboundConfig;

I want to pass state, typeOfClaim, fileTypeID from this first index.tsx to second index.tsx and store those values in variables.

How to pass value from third Component to Home.js in react?

I am new to react so hope this doesn’t sound like a stupid question.

I have a scenario where I have a Home.js with the component that creates a from and a to date range that is then passed to the apiPost.js that retrieves data in that date range.

My problem is getting the values to the Home.js from the apiPost.js after the values have been retrieved.

I should probably note I am not using classes.

I have tried this in the Home.js but it just returns Undefined in let val

(async function () {
      try {
        console.log("fetching data.....");
        let val = await GetValues().then(result => console.log('Home2 ', result));
        console.log("Home", val);
        //console.log("Total is ", val.Total);
        setValue(val);
        console.log('Home state is ',value)
        console.log("Successs: fetching data rendered");
      } catch (err) {
        console.error(err.message);
      }
    })();

Thank you in advance.

Is there anyway to create an alias/pointer to a localStorage value?

I am frequently reading/writing the same localStorage value and it would be nice to create an alias to improve readability. Currently I am doing this.

const ind = localStorage.fileList.findIndex(f => f.fileID === fileID);

localStorage.fileList[ind].settings.lock = false;
localStorage.fileList[ind].objects[2].width = 50;

I would like to do something like this (doesn’t work)

const ind = localStorage.fileList.findIndex(f => f.fileID === fileID);
let x = localStorage.fileList[ind];

x.settings.lock = false;
x.objects[2].width = 50;

How to render rail or train tracks in Azure Maps at all zoom levels?

I am trying to render train locations in Azure Maps. To give more context to the train locations I would like to show the train tracks. However, by default, train tracks only appear when very zoomed in. How can I control the zoom levels that rail or train tracks are displayed?

I have manually explored the JavaScript API and discovered that the default map when looking at Australia has two line-type layers related to rail: “Railway” and “Railway outline”. These can be inspected as follows:

map.map.getLayer('Railway')
map.map.getLayer('Railway outline')

Layers are supposed to support minZoom and maxZoom properties as documented here, but setting these has no effect. Setting other properties, such as colour, works.

The map knows where the tracks are, how to render them, and lets you customise the rendering, how can I stop the disappearing when I zoom out?

Cannot set headers after they are sent to the client but data is being sent

I am new to express.js and I was sending data of a user using mongoose to send data to mongoDB but after I send 1 incorrect data this error pops up and If I try to send a valid user information this error pops up again but the entries are being sent to my mongoDB database.
Case 1:

  • if I send a correct entry : It works
  • if I send another correct entry : It works
  • If I send an incorrect entry : It crashes

Case 2:

  • if I send a correct entry : It works
  • if I send an incorrect entry : It crashes
  • If I send a correct entry : It crashes but it still sends the data to my database

So do I have to reload everytime after it crashes once or there is a better solution to that?

Error:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:387:5)
    at ServerResponse.setHeader (node:_http_outgoing:603:11)
    at ServerResponse.header (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:794:10)
    at ServerResponse.send (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:174:12)
    at ServerResponse.json (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesexpresslibresponse.js:278:15)
    at Connection.onMessage (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:213:9)      
    at MessageStream.<anonymous> (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapconnection.js:59:60) 
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:124:16)  
    at MessageStream._write (D:FilesDesktopProgrammingReactinotebookbackendnode_modulesmongodblibcmapmessage_stream.js:33:9)   
    at writeOrBuffer (node:internal/streams/writable:391:12) {
  index: 0,
  code: 11000,
  keyPattern: { email: 1 },
  keyValue: { email: '[email protected]' },
  [Symbol(errorLabels)]: Set(0) {}
}

Code:
index.js –

const connectToMongo = require('./db');
const express = require('express');
// npm run server

connectToMongo();
const app = express();
const port = 3000;

app.use(express.json());

// * Available Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/notes', require('./routes/notes'));


app.listen(port, () => {
  console.log(`Example app listening on port at http://localhost:${port}`)
})

db.js –

const mongoose = require('mongoose');

const mongoURI = 'mongodb://localhost:27017/iNotebook';

const connectToMongo = () =>{
  mongoose.connect(mongoURI).then(()=>{
    console.log('Connected to Mongo Successfully');
  });
}

module.exports = connectToMongo;

routes/auth.js –

const express = require('express');
const router = express.Router();
const User = require('../models/User');
const { body, validationResult } = require('express-validator');



// * Create A User using: POST "/api/auth/". Doesn't require Auth
router.post('/',[
  body('name', 'Enter a valid name').isLength({min: 3}),
  body('email', 'Enter a valid email').isEmail(),
  body('password', 'Password must be atleast 5 characters').isLength({min: 5})
], (req, res)=>{
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
  }).then(user => res.json(user))
  .catch(err => console.log(err),
  res.json({error: 'Please enter a unique value for Email'}))
});
module.exports = router;

routes/notes.js –

const express = require('express');
const router = express.Router();

router.get('/', (req, res)=>{
  
  res.json([]);
});

module.exports = router;

models/Notes.js –

const mongoose = require('mongoose'); 

const NotesSchema = new Schema({
  title:{
    type: String,
    required: true
  },
  description:{
    type: String,
    required: true
  },
  tag:{
    type: String,
    default: "General"
  },
  date:{
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('notes', NotesSchema);

models/User.js –

const mongoose = require('mongoose'); 
const { Schema } = mongoose;


const UserSchema = new Schema({
  name:{
    type: String,
    required: true
  },
  email:{
    type: String,
    required: true,
    unique: true
  },
  password:{
    type: String,
    required: true
  },
  date:{
    type: Date,
    default: Date.now
  }
});

const User = mongoose.model('user', UserSchema);
User.createIndexes();
module.exports = User;

Can’t solve MulterError: Unexpected field in react/express

I tried to send img file and other text information from React to Express server, save img in aws S3 using multer as middleware, and save img url from S3 and other inform in server DB.
I keep getting MulterError: Unexpected field error while I try upload.single or upload.array in multer or change the Content-type etc… I’ve been trying for hours, now I don’t even know how to modify it.
The way to S3 access is to use access/secret access key in .env as an IAM user.

my react side code

const Item = () => {
  
  const {
 
    register,
    handleSubmit,
    formState: { isSubmitting },
  } = useForm({
    defaultValues: {
      itemName: "",
      imgs: null,
      webpImgs: null,
      price: null,
      category: "",
      brand: "",
      sale: null,
    },
  });

  const onSubmit = async (data) => {
  
    const formData = new FormData();
 
    var sumFile = document.querySelector("#sumFile");
    formData.append("sumFile", sumFile?.files[0]);
 
    const blob = new Blob([data], {
      type: "application/json",
    });
    formData.append("info", blob);

    try {
      addItem(formData).then(async (res) => {
        if (res.status === 200) {
          alert("test");
        } else {
          alert("fail");
        }
      });
    } catch (err) {
      return err;
    }
  };

  return (
    <form className="user-form" onSubmit={handleSubmit(onSubmit)}>
      <select {...register("category")}>
        <option value="a">a</option>
        <option value="b">b</option>
        <option value="c">c</option>
      </select>
      <select {...register("type")}>
        <option value="Short">Short</option>
        <option value="Long">Long</option>
        <option value="Dress">Dress</option>
      </select>

      <input {...register("itemName")} placeholder="itemName" />
      <input
        {...register("file")}
        type="file"
        name="sumFile"
        id="sumFile"
        accept="image/*"
      />
      <input {...register("price")} placeholder="price" />
      <input {...register("brand")} placeholder="brand" />
      <input {...register("sale")} placeholder="sale" />

      <button disabled={isSubmitting}>Add</button>
    </form>
  );
};

express code. I wanted to pass img url to next function here but couldn’t try bc I haven’t saved img to S3 yet.

const express = require("express");
const router = express.Router();
const item = require("../controllers/item");
const { S3Client} = require("@aws-sdk/client-s3");
const dotenv = require("dotenv");
const multer = require("multer");
const multerS3 = require("multer-s3");
const s3 = new S3Client();
dotenv.config();

const upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: "bucket name",
    metadata: function (req, file, cb) {
      cb(null, { fieldName: file.fieldname });
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString());
    },
  }),
});

router.post("/additem", upload.array("sumFile", 2), function (req, res, next) {
  console.log(req.files);
  res.status(200).send("Successfully uploaded ");
});


module.exports = router;

in network req payload

——WebKitFormBoundaryJxBVt4RCvqhg3w9L Content-Disposition: form-data; name=”sumFile”; filename=”a.png” Content-Type: image/png

——WebKitFormBoundaryJxBVt4RCvqhg3w9L Content-Disposition: form-data; name=”info”; filename=”blob” Content-Type: application/json

error detail

Unexpected field MulterError: Unexpected field
at wrappedFileFilter (/Users/home/self/backtest/server/node_modules/multer/index.js:40:19)
at Multipart. (/Users/home/self/backtest/server/node_modules/multer/lib/make-middleware.js:107:7)
at Multipart.emit (node:events:513:28)
at HeaderParser.cb (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:358:14)
at HeaderParser.push (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:162:20)
at SBMH.ssCb [as _cb] (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:394:37)
at feed (/Users/home/self/backtest/server/node_modules/streamsearch/lib/sbmh.js:219:14)
at SBMH.push (/Users/home/self/backtest/server/node_modules/streamsearch/lib/sbmh.js:104:16)
at Multipart._write (/Users/home/self/backtest/server/node_modules/busboy/lib/types/multipart.js:567:19)
at writeOrBuffer (node:internal/streams/writable:392:12)

Unable to perform WebSocket communication using Socket.IO.Client

Want To Do

  • Performe WebSocket using Socket.IO.Client
  • Same thing as following code
  • The code below connects to the WebSocket, receives a message, then sends it and disconnects from the socket.

index.html

<a>Open the console to see stuff, then refresh to initiate exchange.</a>
<script src='script.js'></script>

script.js


const socket = new WebSocket('ws://localhost:3000/ws');

socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});


setTimeout(() => {
    const obj = { hello: "world" };
    const blob = new Blob([JSON.stringify(obj, null, 2)], {
      type: "application/json",
    });
    console.log("Sending blob over websocket");
    socket.send(blob);
}, 1000);

setTimeout(() => {
    socket.send('About done here...');
    console.log("Sending close over websocket");
    socket.close(3000, "Crash and Burn!");
}, 3000);

Problem I’m having

The following is the code I wrote

  const socket = io('ws://127.0.0.1:3000');
  console.log("socket, ", socket);
  socket.on('connect', () => {
    socket.emit('message', 'Hello Server!');
  });

  socket.on('message', (data) => {
      console.log('Message from server ', data);
  });

  setTimeout(() => {
      const obj = { hello: "world" };
      console.log("Sending blob over websocket");
      socket.emit('message', obj);
  }, 1000);

  setTimeout(() => {
      socket.emit('message', 'About done here...');
      console.log("Sending close over websocket");
      socket.close();
  }, 3000);

I think I cannot connect to server.
Following is a Warning

  connected: false,
  recovered: false,
  receiveBuffer: [],
  sendBuffer: [],
  _queue: [],
  _queueSeq: 0,
  ids: 0,
  acks: {},
  flags: {},
  io: Manager {
    nsps: { '/': [Circular *1] },
    subs: [
      [Function: subDestroy],
      [Function: subDestroy],
      [Function: subDestroy]
    ],
    opts: {
      path: '/socket.io',
      hostname: '127.0.0.1',
      secure: false,
      port: '3000'
    },
    setTimeoutFn: [Function: bound setTimeout],
    clearTimeoutFn: [Function: bound clearTimeout],
    _reconnection: true,
    _reconnectionAttempts: Infinity,
    _reconnectionDelay: 1000,
    _reconnectionDelayMax: 5000,
    _randomizationFactor: 0.5,
    backoff: Backoff {
      ms: 1000,
      max: 5000,
      factor: 2,
      jitter: 0.5,
      attempts: 0
    },
    _timeout: 20000,
    _readyState: 'opening',
    uri: 'ws://127.0.0.1:3000',
    encoder: Encoder { replacer: undefined },
    decoder: Decoder { reviver: undefined },
    _autoConnect: true,
    engine: Socket {
      writeBuffer: [],
      setTimeoutFn: [Function: bound setTimeout],
      clearTimeoutFn: [Function: bound clearTimeout],
      secure: false,
      hostname: '127.0.0.1',
      port: '3000',
      transports: [Array],
      prevBufferLen: 0,
      opts: [Object],
      id: null,
      upgrades: null,
      pingInterval: null,
      pingTimeout: null,
      pingTimeoutTimer: null,
      readyState: 'opening',
      transport: [Polling],
      _callbacks: [Object]
    },
    skipReconnect: false,
    _callbacks: {
      '$open': [Array],
      '$packet': [Array],
      '$error': [Array],
      '$close': [Array]
    }
  },
  nsp: '/',
  _opts: {
    path: '/socket.io',
    hostname: '127.0.0.1',
    secure: false,
    port: '1919'
  },
  subs: [
    [Function: subDestroy],
    [Function: subDestroy],
    [Function: subDestroy],
    [Function: subDestroy]
  ]
}

How to connect to server ?
The path section contains socket.io. Is that part the problem?

How might I change the value of a property in an object created by a function? Is this possible in Javascript?

I want to change a value of a property, in this case, lets say the age of a ‘resident’ (a resident has been created by the function “createResident()” following the move-In command) that occurs at the start of a game. If time were to advance, like with the push of a button “advance year”, how can I change the property “Age” to increment by 1. Is it possible for me to create some sort of copy or track the Resident and its properties and have it dynamically change with any given output from a function. I basically want each Resident and its properties to be displayed in HTML, so the age value would be viewed on the browser. I am completely open to revising this entire thing!

Here is my code:


const testTime = document.createElement("testTime");
testTime.classList.add('testTime');
document.body.appendChild(testTime);
testTime.setAttribute("id", "testTime");
var cEBtn = document.createElement("button");
document.body.appendChild(cEBtn);
cEBtn.innerHTML = "Change Year";
cEBtn.setAttribute("id", "cEBtn");
testTime.innerHTML = "Year: 0";
let year = 0;

function changeYear() {
    year++;
    testTime.innerHTML = "Year:" + " " + year;
    return [year];
};

// Move-In resident

let firstName = ["Carol", "Joe", "Bob", "Matthew", "James", 'Bachelor', 'Rogue', "Bobby"]
let lastName = ["Doe", "Smith", "Thomas", "Johnson", "Broad", "Tyler"]
let gender = ["Male", "Female", "Non-binary"]

randomchoice = object => object[Math.floor(Math.random() * object.length)]

const residents = document.getElementById("Residents");

function createResident() {
    let age = Math.floor(Math.random() * (60 - 18) + 18);
    let first_name = randomchoice(firstName);
    let last_name = randomchoice(lastName);
    var Resident = document.createElement("td");
    Resident.style.backgroundColor = "white";

    Resident.id = "Resident" + " " + residentAmount;
   
    const ResidentObj = {
    First_name: first_name,
    Last_name: last_name,
    ID: residentAmount,
    Status: "Alive" || "Dead",
    Age: age,
    Gender: randomchoice(gender),
    get fullName() {
        return ResidentObj.First_name + " " + ResidentObj.Last_name
    }

    }
    
    residents.append(Resident)
        
        Resident.innerHTML = "Name:" + " " + ResidentObj.fullName + "<br>" + "ID:" + " " + ResidentObj.ID + "<br>" + "Age:" + " " + ResidentObj.Age + "<br>" + "Gender:" + " " + ResidentObj.Gender
        + "<br>" + "Status:" + " " + ResidentObj.Status;
}

function moveInRes() {
    residentAmount += 1;
    createResident()

}


moveInRes()
moveInRes()
moveInRes()
moveInRes()

cEBtn.onclick = function called() { 
    changeYear();
}

I have tried removing the “ResidentObj” from the createResident function. However, that causes HTML to not be able to reference individual names, ages, and other attributes. I want these residents to all have different values of attributes at spawn. I know there has to be a roundabout way of doing this. If not, what other languages do you recommend to do more of this procedural framework?

Thanks!