How To Add multiple Button Selections to a Div

So I have A Table With Buttons and match information, I am trying to script a code when I click on the specific button, it adds my selections to div(cart) for example if i click on the first button (1.59), it should add the match Name to the cart (Arsenal-Chelsea) ,The related selection (Arsenal) OR Header Name (Home) and The Value (1.59) in this order

Arsenal-Chelsea
Arsenal
1.59

Plus, I need it to be functional whenever I Re-click on the same button (1.59) it should be able to remove the selection from the cart

here is my html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script type="text/javscript" src="script.js"></script>
    <link rel="stylesheet" href="Style.css">
    <title>Test Sample</title>
</head>

<h1>Sample</h1>


<body>


    <div class="cart" Id="cart">

        <div class ="title" >Bet Slip</div><chr/>
    
            <div id="sel">
                
            <span></span></div><br>
            <span>Selections:</span><br>
    


    
            <button class="bet1">Bet</button><br>
    
    </div>
    
    
    
    <br>
    


    <table id="choose-address-table" class="ui-widget ui-widget-content" border="1">
        <thead>
            <tr class="ui-widget-header " >
                <th>Match</th>
                <th>Home</th>
                <th>Draw</th>
                <th>Away</th>

            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Arsenal-Chelsea</td>
                <td><input type=button class="nr" value="1.59"></td>
                <td><input type=button class="nr" value="3.40"></td>
                <td><input type=button class="nr" value="2.90"></td>
                
        
                </td>
            </tr>
            <tr>
                
                <td>Man United-Man City</td>
                <td><input type=button class="nr" value="2.70"></td>
                <td><input type=button class="nr" value="2.90"></td>
                <td><input type=button class="nr" value="2.50"></td>
    
                    
                </td>
            </tr>
            <tr>
                
                <td>Barcelona-Real Madrdid</td>
                <td><input type=button class="nr" value="3.60"></td>
                <td><input type=button class="nr" value="3.20"></td>
                <td><input type=button class="nr" value="1.95"></td>
    
                    
                </td>
            </tr>







        </tbody>
    </table>



</body>
</html>

here is the script


<script>


$(".nr").click(function() {
    var $item = $(this).closest("tr")  
                       .find(".nr")    
                       .val();        

    $("#cart").append($item);  
    $("#cart").append("<div class='cart' Id='cart'>");


});


    </script>

I want to DM the owner of the server once the bot has been invited

So I’m looking for a way to get my bot to message the owner of the server its been added too. After looking at lots of stackoverflow answers, they all looked similar to the following code:

client.on('guildCreate', guild =>{
    guild.author.send('Hello');
});

However, when I tried this and added the bot to another server, the bot not only crashed but I got the following error:

 owner.send('HI');
          ^

TypeError: Cannot read properties of undefined (reading 'send')

Can someone please help me out here. Thanks in advance.

ThreeJS – on click move camera doesn’t work

I’m new with ThreeJS, so hopefully someone can help.

I’m trying to move my camera when I click the button, but nothing happens and I have no errors.

This is the function I have that should move camera by 200 in all directions, but no such effect:

var button = document.getElementById("button");
button.addEventListener("click", function() {
    var tween1 = new TWEEN.Tween(camera.position)
    .to({
        x : 200,
        y : 200,
        z : 200
    } , 1000)
    .easing(TWEEN.Easing.Linear.None)
    .start();
});

What am I doing wrong?

Here is the entire ThreeJS script for better context:

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 4;

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = true;

var keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);

var fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);

var backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();

scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath('assets/');
mtlLoader.setPath('assets/');
mtlLoader.load('r2-d2.mtl', function (materials) {

    materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('assets/');
    objLoader.load('object.obj', function (object) {

        scene.add(object);
        object.position.y -= 0;

    });

});

var animate = function () {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render(scene, camera);
};

animate();

var button = document.getElementById("button");
button.addEventListener("click", function() {
    var tween1 = new TWEEN.Tween(camera.position)
    .to({
        x : 200,
        y : 200,
        z : 200
    } , 1000)
    .easing(TWEEN.Easing.Linear.None)
    .start();
});

AngularJS assertion failure on SharePoint React Script Editor Webpart SPFx Webpart

I have a Microsoft SharePoint 2013 application which consists of AngularJS customized application aspx pages. The application works perfectly fine on SP13.

But now the requirement is to move to SPO Modern Teams site. To prevent a lot of SPFx re-development and time lag, I have used a React Script Editor Webpart SPFx Webpart where I can simply copy the HTML and references that are already developed and working script files.

I am facing an intermittent issue where only on the first page load, it gives the below error:

Error: [ng:areq] Argument ‘FormCtrl’ is not a function, got undefined

When I refresh again, everything loads properly and works fine. I am unable to troubleshoot and figure out the issue trying multiple combinations and seek for help with this community.

Below is how the application is built on SharePoint 2013 (which works fine) but intermittently when moved to SPO React Script Editor Webpart:

  • SharePoint aspx page in Pages library.
  • Content Editor WebPart with reference to text file containing HTML.
  • Reference to jQuery, AngularJS, etc. and custom script files in HTML.
  • Custom Script files as:
  1. An App File with definition to the app that is declared in the HTML as ng-app

    var app = angular.module('myApp', ['ngRoute']);
  2. A Constants file that is used in the controller

    app.constant('config', {
     ListName: 'This is the name of the list'
     });
  3. A service file. All REST API calls and common methods are defined here and called from controller

     
     app.service('DataAccessLayer', ['$http', '$q', function ($http, $q) {
             this.method1(){
             ....
             }
    
             this.method2(){
             ....
             }
         });
     
     
  4. The main controller file which has the functionality written:

app.controller('FormCtrl', function ($scope, config, DataAccessLayer) {});

Why fetch() sends an empty body on server without properties? [closed]

I’m sending data from the form on server but obj is empty
I tried app.use(express.json()) as well, but it’s not working?


javascript

            btn.addEventListener('click',(e)=>{
            e.preventDefault();
            let form = document.forms.myForm;
            let name1 = form.elements.one.value;
            let name2 = form.elements.two.value;
            let name3 = form.elements.three.value;
            
            let obj = {
                pers1: name1, pers2: name2, pers3: name3
            }
            fetch('http://localhost:8000',{
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(obj)
            })
            .then((response) => {
            return response.json();
            })
            .then((data) => {
            console.log(data);
            });
        })


app.use(express.urlencoded({extended: true }));


const createPath = (page) => path.resolve(__dirname,'pages',`${page}.html`);
app.get('/',(req,res)=>{
    res.sendFile(createPath('index'));
})
app.post('/',(req,res)=>{
    console.log(req.body);
    res.send(req.body);
})



[enter link description here][1]
[1]: https://justCode.com

Any way to get a currentTime value prior to the seek on HTMLMediaElement?

Let’s say our app is using the default video player on Safari.

When a user is playing a video and then attempts to move to a different position of the video using the seek bar, it seems like pause event is fired first, and then we’ll get seeking and seeked events fired.

I am wondering if we can get the currentTime value prior to the seek. For instance, assuming that a user jumps from t = 7 to t = 42 using the seek bar, I want to get 7 as the currentTime value somehow.

I expected that we could get this value by accessing currentTime property inside the pause event handler that is invoked right after the seek like the following:

const video = document.querySelector('#myvideo');
video.addEventListener('pause', () => {
  // I expected that the `video.currentTime` here has the "previous" position,
  // but it already points to the new position
  console.log(video.currentTime);
});

but unfortunately the currentValue was already updated to the new value at that point.

Is there any good way to achieve it?

React: Passing Props not working. Am I missing something?

as you may get from the title, passing props in react is not working. And i don´t get why.

import styled from 'styled-components';


const Login = (props) => {
    return<div>Login</div>

}

export default Login;

On my App.js page here is the following:

import './App.css';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from './components/Login.js';

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path="/" >
            <Login />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

Problem: if i start the script and render the page, nothing is shown. What am I doing wrong?

Replace each occurrence of character/word with different word in javascript

var string = "Please click on dashboard and then open the dashboard details to verify your details on the data";
var stringArray = ["dashboard" , "dashboard" , "data"]
var replaceArray = ["apple collection" , "delta collection" , "data collection"]

I have a string and 2 arrays like above. I need to replace my string with rescpect to array items. stringArray defines the words to be replaced and replaceArray defines the words should be after repalce. Like first occurance of dashboard should be replaced with “apple collection” and second occurance of “dashboard” should be replaced with “delta collection” and “data” should be replaced with “data collection”.

I tried to findout the word in string and replace it with replaceArray element using replace/replaceAll, working fine for single occurance word, but for multiple occurances it is not working.

Anyone help me to resolve this.

Output :

string = "Please click on apple collection and then open the delta collection details to verify your details on the data collection";

is there any way to format d3js graph

I have created a graph and it’s look tangled

        const data ={
    "ok": true,
    "degree": 2,
    "nodes": [
        {
            "id": 19,
            "label": "1",
            "type": "Config"
        },
        {
            "id": 29,
            "label": "2",
            "type": "Model"
        },
        {
            "id": 27,
            "label": "3",
            "type": "Model"
        },
        {
            "id": 24,
            "label": "4",
            "type": "Model"
        },
        {
            "id": 17,
            "label": "5",
            "type": "Component"
        },
        {
            "id": 22,
            "label": "6",
            "type": "Config"
        },
        {
            "id": 21,
            "label": "7",
            "type": "Config"
        },
        {
            "id": 20,
            "label": "8",
            "type": "Config"
        },
        {
            "id": 15,
            "label": "9",
            "type": "Component"
        },
        {
            "id": 11,
            "label": "10",
            "type": "Technology"
        },
        {
            "id": 10,
            "label": "11",
            "type": "Technology"
        },
        {
            "id": 13,
            "label": "12",
            "type": "Component"
        },
        {
            "id": 9,
            "label": "13",
            "type": "Technology"
        },
        {
            "id": 8,
            "label": "14",
            "type": "Technology"
        },
        {
            "id": 2,
            "label": "15",
            "type": "Technology"
        }
    ],
    "relationships": [
        {
            "id": 40,
            "label": "FRIEND",
            "source": 19,
            "target": 29
        },
        {
            "id": 38,
            "label": "FRIEND",
            "source": 19,
            "target": 27
        },
        {
            "id": 35,
            "label": "FRIEND",
            "source": 19,
            "target": 24
        },
        {
            "id": 24,
            "label": "HAS",
            "source": 19,
            "target": 17
        },
        {
            "id": 33,
            "label": "HAS",
            "source": 22,
            "target": 17
        },
        {
            "id": 30,
            "label": "HAS",
            "source": 21,
            "target": 17
        },
        {
            "id": 27,
            "label": "HAS",
            "source": 20,
            "target": 17
        },
        {
            "id": 23,
            "label": "HAS",
            "source": 19,
            "target": 15
        },
        {
            "id": 29,
            "label": "HAS",
            "source": 21,
            "target": 15
        },
        {
            "id": 17,
            "label": "CONTAINED",
            "source": 15,
            "target": 11
        },
        {
            "id": 16,
            "label": "CONTAINED",
            "source": 15,
            "target": 10
        },
        {
            "id": 8,
            "label": "INSTALLED_IN",
            "source": 11,
            "target": 15
        },
        {
            "id": 6,
            "label": "INSTALLED_IN",
            "source": 10,
            "target": 15
        },
        {
            "id": 22,
            "label": "HAS",
            "source": 19,
            "target": 13
        },
        {
            "id": 25,
            "label": "HAS",
            "source": 20,
            "target": 13
        },
        {
            "id": 21,
            "label": "CONTAINED",
            "source": 19,
            "target": 13
        },
        {
            "id": 12,
            "label": "CONTAINED",
            "source": 13,
            "target": 9
        },
        {
            "id": 11,
            "label": "CONTAINED",
            "source": 13,
            "target": 8
        },
        {
            "id": 10,
            "label": "CONTAINED",
            "source": 13,
            "target": 2
        },
        {
            "id": 5,
            "label": "INSTALLED_IN",
            "source": 9,
            "target": 13
        },
        {
            "id": 2,
            "label": "INSTALLED_IN",
            "source": 8,
            "target": 13
        },
        {
            "id": 1,
            "label": "INSTALLED_IN",
            "source": 2,
            "target": 13
        }
    ]
}
         const map1 = data.nodes.map(x => x.type);
        const colScale = d3.scaleOrdinal(d3.schemeCategory10).domain(map1);
       
       const width = 1152;
        const height = 1152;
        let maxLinkOcc = {};
        let linkDistance = 300
        let nodeRadius = 35;
        let lineHeight = 12;

      

        if (data.relationships.length > 0) {
            computeLinkNumber(data.relationships, maxLinkOcc);
        }

        const simulation = d3
            .forceSimulation(data.nodes)
            .force("link", d3.forceLink(data.relationships).id(d => d.id).distance(linkDistance).strength(0.1))
            .force("charge", d3.forceManyBody())
            .force("center", d3.forceCenter(width / 2, height / 2))
            .force("collide", d3.forceCollide(30).iterations(10))
            .on("tick", ticked);

        const svg = d3.select(".global")
            .append('svg')
            .attr('width', window.innerWidth)
            .attr('height', window.innerHeight)
            .attr("viewBox", [0, 0, window.innerWidth, window.innerHeight])
            .attr("style", "max-width: 100%; height: auto; height: intrinsic;")
            .attr("font-family", "sans-serif")
            .attr("font-size", 10)
            .call(d3.zoom().scaleExtent([1 / 2, 8]).on("zoom", zoomed))
            .append("g");

        

        function zoomed(event) {
            svg.attr("transform", event.transform);
        }

        const link = svg.append("g").selectAll("g").data(data.relationships).enter().append("g");

        const paths = link
            .append("path")
            .attr("class", "links")
            .attr("stroke", "#aaa")
            .attr("stroke-width", "3px")
            .attr("id", d => d.id)
            .attr("style", "fill: none;");

        const texts = link.append("text")
            .append("textPath")
            .attr("href", d => "#" + d.id)
            .attr("startOffset", '50%').append("tspan").attr("stroke", "black").attr("font-weight", "bold")
            .attr("style", "text-anchor: middle; font: 10px sans-serif")
            .text(d => d.label + " ►")
            .attr("dy", 3)

        const node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("g").data(data.nodes)
            .enter().append("g").attr("cursor", "move")
            .call(d3.drag()
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended))

        node.append("circle")
            .attr("class", "node")
            .attr("r", nodeRadius)
            .attr("stroke-width", 3)
            .attr("stroke", (d, _i) => colScale(d.type))
            .attr("fill", (d, _i) => colScale(d.type))
            .on("click", (_e, _data) => {
                console.log("this.state.nodeId", this.state.nodeId, _data.id)
                let num = this.state.nodeId === null ? 0 : 1;
                this.setState((prevState) => ({
                    degree: prevState.nodeId === _data.id ? prevState.degree + 1 : num,
                    nodeId: _data.id
                }
                ), () => {
                    this.nodeSelected(_data, this.state.degree)
                })
            })


        appendText(node, d => d.label, nodeRadius - 10);

        node.selectAll(".fitted-text")
            .attr("fill", "white")
            .selectAll("tspan")
            .attr("font-weight", "bold");


        function computeLinkNumber(links, maxLinkOcc) {
            //sort links by source, then target
            links.sort(linkSort);
            //any links with duplicate source and target get an incremented 'linknum'
            for (var i = 0; i < links.length; i++) {
                if (
                    i !== 0 &&
                    links[i].source === links[i - 1].source &&
                    links[i].target === links[i - 1].target
                ) {
                    links[i].linknum = links[i - 1].linknum + 1;
                    maxLinkOcc[links[i].source + "->" + links[i].target] += 1;
                } else {
                    links[i].linknum = 1;
                    maxLinkOcc[links[i].source + "->" + links[i].target] = 1;
                }
            }
        }


        function getLinkPath(source, target, linknum, inv, uniqueLink) {
            let dx = target.x - source.x,
                dy = target.y - source.y,
                dist = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

            var c1 = closestPointOnCircleEdge(source, target, nodeRadius);
            var c2 = closestPointOnCircleEdge(target, source, nodeRadius);

            let startX = c1.x,
                startY = c1.y,
                endX = c2.x,
                endY = c2.y,
                centerX = (startX + endX) / 2,
                centerY = (startY + endY) / 2,
                angle = Math.atan2(endY - startY, endX - startX);

            if (uniqueLink) {
                return `M${startX} ${startY} L${endX} ${endY}`;
            }

            let p = Math.max(Math.min(30, 10000 / dist), 25);

            let mx = Math.sin(angle) * (inv * linknum * p) + centerX;
            let my = -Math.cos(angle) * (inv * linknum * p) + centerY;

            return `M${startX} ${startY} C${startX} ${startY}, ${mx} ${my} , ${endX} ${endY}`;
        }


        function linkSort(a, b) {
            if (a.source > b.source) {
                return 1;
            } else if (a.source < b.source) {
                return -1;
            } else {
                if (a.target > b.target) {
                    return 1;
                }
                if (a.target < b.target) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }

        function ticked() {
            updateNodes();
            updateLinks();
        }

        function updateNodes() {
            node.attr("transform", d => `translate(${d.x},${d.y})`);
        }

        function updateLinks(nodeId) {

            let updatedLinks = data.relationships.filter(d =>
                nodeId ? d.source.id === nodeId || d.target.id === nodeId : true
            );

            let linkPath = svg.selectAll(".links").data(updatedLinks, d => d.id);


            linkPath.attr("d", function (d, _i) {

                let linkTspan = d3
                    .select(this.parentNode)
                    .select("textPath")
                    .select("tspan");


                if (d.source.id === d.target.id) {
                    let dr = nodeRadius / 2 + 5 + d.linknum * 7;
                    return (
                        "M" +
                        (d.source.x - 1) +
                        "," +
                        d.source.y +
                        " A " +
                        dr +
                        "," +
                        dr +
                        " 0 1,1 " +
                        (d.target.x + 1) +
                        "," +
                        d.target.y
                    );
                } else {
                    let a1 = maxLinkOcc[d.source.id + "->" + d.target.id];
                    let a2 = maxLinkOcc[d.target.id + "->" + d.source.id];
                    let uniqueLink = a1 + a2 === 1 || (a1 === 1 && !a2);

                    let source = d.source;
                    let target = d.target;

                    if (source.x > target.x) {
                        linkTspan.text(d => "◄ " + d.label);

                        target = d.source;
                        source = d.target;
                        return getLinkPath(source, target, d.linknum, 1, uniqueLink);
                    } else {
                        linkTspan.text(d => d.label + "  ►");
                        return getLinkPath(source, target, d.linknum, -1, uniqueLink);
                    }
                }
            });
        }

        function dragstarted(event, d) {
            if (!event.active) simulation.alphaTarget(0.3).restart();
            d.fx = d.x;
            d.fy = d.y;
        }

        function dragged(event, d) {
            d.fx = event.x;
            d.fy = event.y;
        }

        function dragended(event) {
            if (!event.active) simulation.alphaTarget(0);
        }

        function closestPointOnCircleEdge(A, B, r) {
            const a1 = B.x - A.x;
            const b1 = (B.x - A.x) ** 2 + (B.y - A.y) ** 2;

            let x = A.x + r * (a1 / Math.sqrt(b1));

            const a2 = B.y - A.y;
            const b2 = (B.x - A.x) ** 2 + (B.y - A.y) ** 2;

            let y = A.y + r * (a2 / Math.sqrt(b2));

            return { x, y };
        }


        function appendText(selection, textParam, radiusParam) {
            const getRadius = typeof radiusParam === "function"
                ? radiusParam
                : function () { return radiusParam };

            const getText = typeof textParam === "function"
                ? textParam
                : function () { return textParam };

            selection.each(function (_d) {
                d3.select(this)
                    .selectAll(".fitted-text")
                    .data([{}])
                    .enter()
                    .append("text")
                    .attr("class", "fitted-text").attr("style", "text-anchor: middle; font: 10px sans-serif");
            })

            let text = selection.select(".fitted-text");

            text.datum(function (d) {
                var lines = getLines(getText(d));
                d.lines = lines.lines;
                d.textRadius = lines.textRadius;
                return d
            });

            text.selectAll("tspan")
                .data((d) => d.lines)
                .enter()
                .append("tspan")
                .attr("x", 0)
                .attr("y", (d, i) => (i - d.linesLength / 2 + 0.8) * lineHeight)
                .text((d) => d.text);

            text.attr("transform", function (d) {
                var scale = 1;
                if (d.textRadius !== 0 && d.textRadius) {
                    scale = getRadius(d) / d.textRadius;
                }
                return "translate(" + 0 + "," + 0 + ")" + " scale(" + scale + ")"
            });
        }

        function getLines(text) {
            if (text === undefined || text === null) {
                return { lines: [] }
            }

            text = String(text);

            let words = text.split(/s+/g); // To hyphenate: /s+|(?<=-)/
            if (!words[words.length - 1]) words.pop();
            if (!words[0]) words.shift();
            let targetWidth = Math.sqrt(measureWidth(text.trim()) * lineHeight);
            let line;
            let lineWidth0 = Infinity;
            let lines = [];

            for (let i = 0, n = words.length; i < n; ++i) {
                let lineText1 = (line ? line.text + " " : "") + words[i];
                let lineWidth1 = measureWidth(lineText1);
                if ((lineWidth0 + lineWidth1) / 2 < targetWidth) {
                    line.width = lineWidth0 = lineWidth1;
                    line.text = lineText1;
                } else {
                    lineWidth0 = measureWidth(words[i]);
                    line = { width: lineWidth0, text: words[i] };
                    lines.push(line);
                }
            }

            let textRadius = 0;
            for (let i = 0, n = lines.length; i < n; ++i) {
                let dy = (Math.abs(i - n / 2 + 0.5) + 0.5) * lineHeight
                let dx = lines[i].width / 2;
                textRadius = Math.max(textRadius, Math.sqrt(dx * dx + dy * dy));
            }

            return {
                "lines": lines.map(function (d) {
                    return { "text": d.text, "linesLength": lines.length }
                }),
                "textRadius": textRadius
            }
        }

        function measureWidth(text) {
            const context = document.createElement("canvas").getContext("2d")
            return context.measureText(text).width;
        }
<!DOCTYPE html>
<html>
   <head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.5.0/d3.min.js"></script>
   </head>

   <body>
      <div class="global"> </div>
      
   </body>
</html>

But I want to format this graph like this any lead
I also go through https://github.com/d3/d3-force documentation but I didn’t get it
Thank you so much

enter image description here

GET vs POST file download using express.js – changing the REST verb results in larger and incorrect file

My situation is that in one of my services I provide many REST GET APIs to allow the downloading of files (typically xlsx).

In a new API I have a POST API which does exactly the same thing as another GET API (I’ve copied pasted the code line by line), except that it’s using a POST instead of a GET

export async function postDownloadMyFile (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<Response> {

  ... // xlsx workBook creation code
  const buffer =  await workBook.xlsx.writeBuffer();

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  res.setHeader('Content-Disposition', 'attachment; filename=' + 'MyFile.xlsx');
  res.write(buffer, 'binary');
  res.end();

  return res;
}

but when the frontend client makes a request to download the file, the file comes back about twice the size than if I used a GET request and cannot be opened (presumably wrong format/buffer written out wrong).

changing the frontend and backend to use a GET (not modifying the body of the function above) ‘fixes’ the issue.

Are there some additional headers I’m meant to be setting?

Thanks

Sending an object from Consumer to Producer

I am working on a Producer/Consumer system. The producer generates a random expression of two positive integers "2+2=" sends it to the Consumer and then the Consumer computes and sends the solved expression "2+2=4" back to the Producer
I am stuck at the part where I have to send the solved expression back to the Producer. How would I do that?

My Producer:

var XMLHttpRequest = require('xhr2');
const URL = "http://localhost:5000/"
let firstNumber = Math.floor(Math.random() * 10);
let secondNumber = Math.floor(Math.random() * 10);
const express = require('express');
const app = express();



// excecuting random addition
const finalExpression = firstNumber + "+" + secondNumber + "="

console.log(finalExpression);

var xhr = new XMLHttpRequest();
xhr.open("POST", URL, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    expression: finalExpression
}))

My Consumer:

const express = require('express')
const app = express()
app.use(express.json())

app.post('/', (req, res) => {
  console.log(req.body.expression);
  arr = req.body.expression.split("")
  console.log(parseInt(arr[0]) + parseInt(arr[2]))
  // res.send(parseInt(arr[0]) + parseInt(arr[2]))
})

app.listen(5000, () => console.log())

What do I have to do within the consumer to send the solved expression to the producer?
If I uncomment // res.send(parseInt(arr[0]) + parseInt(arr[2]))
I get this result:

express deprecated res.send(status): Use res.sendStatus(status) instead index.js:21:7  
RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status 

Why can’t I access data() using ‘this’ directly?

I work on Vue2 app. What I have noticed is that sometimes I can’t access elements stored in data() using this directly in my code. What I mean by that is that sometimes I need to assign this... to a variable inside a method to make it work instead of simply refer to data element by this.

I created reproducible example here: https://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-this-usage-trhd72?file=/src/components/ZimModel.vue

Please take a look at method addRegals(). I used this.size everywhere in this method but what I got in console is this error:

[Vue warn]: Error in callback for watcher “regalsTotalNumber”:
“TypeError: this is undefined”

I don’t get why there’s an error if I simply refer to data() element using this.
To make my code work you need to uncomment code in this method (and comment not working lines). It all starts with assignning data element to variable:

var size = this.size;

I don’t understand why I need to make a variable and assign this.size to it instead of explicitly using this in my method. Same situation with var tiles = this.thetiles in the same method (I also need to assign it to var to make it work in this method).

Method addRegals is triggered in watcher. Maybe here is a problem?

PS. Please type ‘120’ as length, ’55’ as width in input fields (give it a few sec to show the grid on a screen), then type some number in ‘Regals number’ field.

Node js error return fn.apply(this, arguments);

My import code using node js import export route.js

It works in the browser, but the console drops this error, I could not solve it
cmd

node_modulesexpresslibrouterindex.js:646
return fn.apply(this, arguments);
^
TypeError: fn.apply is not a function
at C:UsersatalaOneDriveMasaüstüatalaynode_modulesexpresslibrouterindex.js:646:15
at next (C:UsersatalaOneDriveMasaüstüatalaynode_modulesexpresslibrouterindex.js:216:14)
at Function.handle (C:UsersatalaOneDriveMasaüstüatalaynode_modulesexpresslibrouterindex.js:175:

This is code :

import { default as express } from "express";
import auth from "./auth/auth.js";
import user from "./user/user.js";
import clup from "./clup/clup.js";    

const router = express.Router();
            
router.use("/auth", auth);
router.use("/user", user);
router.use("/clup", clup);
 export default router;