How do I load my HTML and CSS file with my NODEJS server?

I am running a nodejs server file, code below. Currently the code you see does not have the HTML or CSS referenced because I don’t know how to do it.

const http = require('http');

// Create an instance of the http server to handle HTTP requests
let app = http.createServer((req, res) => {
    // Set a response type of plain text for the response
    res.writeHead(200, {'Content-Type': 'text/plain'});

    // Send back a response and end the connection
    res.end('Hello World!n');
});

// Start the server on port 3000
app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');

In a folder that looks like this

I have already searched online for hours, looked at previous stackoverflow posts, and I still haven’t found the answer. I got the HTML file to load at one point, but I was not able to get the CSS file to load.

Trying connection with PagSeguro API and i have cors Problem

I’m trying conect my website with PagSeguro API. In Insomnia the request works, but in my website, the cors is the problem.

Problem:
x

Access to XMLHttpRequest at 'https://sandbox.api.pagseguro.com/charges' from origin 'https://mobile-andre-luis.web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

buyCartela.js:107 POST https://sandbox.api.pagseguro.com/charges net::ERR_FAILED

Code Section:

const request = new XMLHttpRequest();
const body = {
        "reference_id": ``,
        "description": ``,
        "amount": {
            "value": 200,
            "currency": "BRL"
        },
        "payment_method": {
            "type": "CREDIT_CARD",
            "installments": 1,
            "capture": true,
            "soft_descriptor": "Cartela do Bode da Sorte",
            "card": {
                "number": ``,
                "exp_month": ``,
                "exp_year": ``,
                "security_code": ``,
                "holder": {
                    "name": ``
                }
            }
        },
        "notification_urls": [
            "http://127.0.0.1:5500/form/buyVerify.html"
        ],
        "metadata": {
            "idVendedor": "Papai Noel",
            "idCartela": ``,
            "nameComprador": ``,
            "phoneComprador": ``,

        }
    };


    const url = `https://sandbox.api.pagseguro.com/charges`;
    request.open("POST", url, true);
    request.setRequestHeader("Access-Control-Allow-Origin","*");
    request.setRequestHeader("Content-type","application/json");
    request.setRequestHeader("Authorization","x");
    request.setRequestHeader("x-api-version","4.0");
    request.send(body);

    console.log(request.response)

xhttp.send works once but fails the 2nd time

I have the following javascript that works happily the 1st time but fails the second time..

    xhttp = new XMLHttpRequest();               
    xhttp.open("POST","FINDMOVES",false);
    xhttp.send(text);       

This send is actually being received by the server and a respone is written by the server. The server is my own and written in assembler.
The java console reports:-

POST http://localhost:1024/FINDMOVES net::ERR_EMPTY_RESPONSE
Uncaught DOMException: Failed to execute ‘send’ on ‘XMLHttpRequest’: Failed to load ‘http://localhost:1024/FINDMOVES’.

This code works happily where it is used in other programs.

I am aware that:- “[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience” but it is not java’s decision as to what my end user experience is like. It is mine.

Anyone got any clues ??

Is there a reason to prefer Symbol.keyFor() over Symbol.prototype.description?

In JavaScript, I can create Symbol -primitives like this:

const ex1 = Symbol('example1');
const ex2 = Symbol.for('example2');

And I can get the original string that was used to create the Symbol by accessing the Symbol.prototype.description, or by calling the Symbol.keyFor() -method like so:

ex1.description; // 'example1'
ex2.description; // 'example2'
// OR
Symbol.keyFor(ex1); // undefined
Symbol.keyFor(ex2); // 'example2'

My questions are;

  • Is there any difference between the two methods, other than Symbol.keyFor not working for Symbols that are not in the global registry (i.e. created from Symbol.for())? It seems to me they are otherwise used to achieve the exact same thing.
  • Is there a reason to ever prefer using Symbol.keyFor() instead of Symbol.prototype.description? Since the description works for all Symbols, while keyFor works only for ones in the global registry.

Why does bind() work so inconsistently in Vue template event handlers?

When experimenting with a bit of fancy syntax in my templates today I came across a confusing behaviour of the bind() function in Vue event handlers.

Ignoring any possibly bad practices and the fact that the bind is completely pointless here, please look at the following 2 code samples.

1.

<template>
  <button @click="(() => console.log('this gets logged')).bind()"></button>
</template>

<script>
export default {
  computed: {
    console: () => console,
  },
}
</script>
<template>
  <button @click="myFunc.bind()"></button>
</template>

<script>
export default {
  methods: {
    myFunc () { console.log("this doesn't get logged") }
  }
}
</script>

Code sample 1 properly logs an output to the console when clicking the button, but for some reason sample 2 doesn’t log anything. Why?

Why’s my response coming back correctly the first log but later on it changes to a 1?

I’m facing a very weird issue where my response comes back correctly during the first log but later on it changes to a 1 when the console.log(data); logs data to the console.

The screenshot shows the pattern:

enter image description here

If you expand the very first array underneath where it says data below from userEffect inside Gallery.js , the data shows up as intended

Then there’s the response array from App.js which also appears as intended.

Lastly, the response magically gets converted to a 1 from inside Gallery.js and I’m not sure how. I’ve ran out of options on how to troubleshoot this and resolve it where it doesn’t get converted to a 1.

What am I doing wrong? I’m open to any code improvements and any other suggestions for better practice :).

Here’s App.js:

import { useEffect, useState } from 'react';
import { BrowserRouter as Router, Switch, Route, useHistory} from 'react-router-dom';
import ReactDOM from 'react-dom';
import '../../sass/HomePage/homePage.scss';
import LoginRegister from "./LoginRegister/LoginRegister";
import Gallery from "./Gallery/Gallery";
import Cookies from 'js-cookie';

const App = () => {
    const [uploadsData, setUploadsData] = useState([]);
    let { push } = useHistory();
    let authToken = Cookies.get('token');

    useEffect(() => {
        getUploads();
    },[])

    function getUploads() {
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        }

        axios.get('http://localhost:8005/api/get-uploads', {headers})
            .then(resp => {
                let uData = uploadsData.push(resp)
                setUploadsData(uData);
                console.log(uploadsData);
                if (authToken !== null) {
                    push('/gallery');
                } else {
                    console.log("User's NOT authenticated, returning to login view");
                    push('/');
                }
            }).catch(error => {
            console.log(error);
        })
    }

    return (
        <>
            <Switch>
                <Route exact path="/" component={LoginRegister} />
                <Route component={() => <Gallery data={uploadsData}/>} />
            </Switch>
        </>
    );
}

export default App;

if (document.getElementById('example')) {
    ReactDOM.render(<Router><App/></Router>, document.getElementById('example'));
}

Here’s Gallery.js:

import React, {useEffect} from 'react';

const Gallery = ( {data} ) => {
    useEffect(() => {
        console.log("FROM App.js INSIDE Gallery.js");
        console.log(data);
    }, []);

    return (
        <>
            <h1>test</h1>
        </>
    );
}

export default Gallery;

Javascript remove style using giving it a id or a class

so I have this HTML code where I hide the body of the website using

    <style>
        body{
          display: none;
        }
    </style>

    <body>
    <p>Something..</p>
    </body>

but now I want to remove this using Javascript without giving the body an ID or a class. As a solution I’ve tried the following but it is not working.

document.getElementsByTagName("body")[0].removeAttribute("style");

Any help is appreciated. Thanks.

How to scroll to top on route change with react router dom v6?

How to scroll to top on route change with react router dom v6?

I have tried this, react-router scroll to top on every transition, which was my solution to make my page scroll to top on route change when I use react-router-dom v5. Now, I am using react-router-dom v6 and this solution does not work.

I tried React-router v6 window.scrollTo does not work and does not work for me.

I tried https://github.com/remix-run/react-router/issues/7365, which is to use the preload prop to trigger the scrollTo(0,0), also does not work for me.

TinyMCE droping html element not allowed with Chrome and Edge

I’ve an issue with Chrome and Edge, about dropping. I have on the right side of my html page, html elements I can drop. On the left side, the tinymce editor. Everything about the editor is set correctly, I have look up for a lot of solutions to resolve my issue, but without success.

The aim is to drag an element from the right, and to drop it on the editor. If i have some text on the editor, it has to be dropped at the caret position of the editor where the mouse with the dragging element is. With firefox, it works well, I have no problems.

Issues with Chrome and Edge:

  • When I have dragged the element, and I start to go in the editor, the css cursor is ‘not-allowed’
  • I added the parameter auto_focus : 'tinyid' at the initialization of the editor (no need to do it on Firefox), where tinyid is the id of the textarea containing the tinymce editor.
  • The solution I had, was to click at a caret position in the editor where I want to drop my element, to start dragging my element, but to not go in the editor, and to drop it after dragging it. It will appear at the caret position i clicked on before.

About solutions I tried:

To set the focus

  • tinyMCE.activeEditor.focus();
  • tinymce.execCommand("mceFocus", false, "tinyid");
  • tinyMCE.get('tinyid').focus();

To get the selection and the caret position with:

  • var objSelection = tinyMCE.activeEditor.selection.getSel();
  • var intCaretPosition = objSelection.anchorOffset;

But all of this is not working. I repeat it works on Firefox. To drag and drop, I use this:

$('.blocUndragged') 
.bind('dragstart', function(event, ui){
    // start
    tinymce.execCommand("mceFocus", false, "tinyid");
    })
.bind('drag', function(event, ui){
    // while 
    tinymce.execCommand("mceFocus", false, "tinyid");
    })
.bind('dragend',   function(event, ui){
    // end
    tinymce.execCommand("mceFocus", false, "tinyid");
    moveElementDraggedIntoEditor(event);});

The function moveElementDraggedIntoEditor(event), is a function where I reworked the html element I dropped, to reformate it.

If you need more precisions, I will try to add some codes.

Thank you for trying to find a solution about my issue.

threejs how to adjust 3d object camera position on scroll

hey guys i am new to threejs and i am currently trying to adjust my camera angle such that it pulls itself backwards on scroll up to a certain level. i am trying to make it such that the 3d object becomes smaller on scroll by adjusting the camera angle. is there anyway to do that? thanks in advance

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  

  <body>
    <script type="module">
        import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
        
        import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
        import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/GLTFLoader.js';
        import { RGBELoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/RGBELoader.js';
        
        var container, controls;
        var camera, scene, renderer, mixer, clock;
        var obj
        
        init();
        animate();
        
        function init() {
        
          container = document.getElementById( 'test' );
          document.body.appendChild( container );
          
          

          camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 1000 );
          camera.position.set(0, 20, 30);

        
          scene = new THREE.Scene();
          scene.background = new THREE.Color(0xffffff);
          var light = new THREE.HemisphereLight(0xffffff,0x000000,10);
          scene.add(light);



          
          clock = new THREE.Clock();
        
              // model
          
              var loader = new GLTFLoader();
              loader.load( 'dinosaur.glb', function ( gltf ) {
        
                obj = scene.add( gltf.scene );
        
                mixer = new THREE.AnimationMixer( gltf.scene );
                
                gltf.animations.forEach( ( clip ) => {
                  
                    mixer.clipAction( clip ).play();
                  
                } );
        
              } );
        
        
          renderer = new THREE.WebGLRenderer( { antialias: true } );
          renderer.setPixelRatio( window.devicePixelRatio );
          renderer.setSize( window.innerWidth, window.innerHeight );
          renderer.toneMapping = THREE.ACESFilmicToneMapping;
          renderer.toneMappingExposure = 0.8;
          renderer.outputEncoding = THREE.sRGBEncoding;
          container.appendChild( renderer.domElement );
        
        
          controls = new OrbitControls( camera, renderer.domElement );
          controls.minDistance = 2;
          controls.maxDistance = 10
          controls.target.set( 0, 0, - 0.2 );
          controls.update();
        
          window.addEventListener( 'resize', onWindowResize, false );


          function rotateFunction() {
        obj.rotation.y += 0.02;        
        console.log(obj)
        
      }

      document.addEventListener('scroll', function(e) { rotateFunction() });


        
        }
        function onWindowResize() {
          camera.aspect = window.innerWidth / window.innerHeight;
          camera.updateProjectionMatrix();
        
          renderer.setSize( window.innerWidth, window.innerHeight );
        }
        
        //
        
        function animate() {
          requestAnimationFrame( animate );
          var delta = clock.getDelta();
          if ( mixer ) mixer.update( delta );
          renderer.render( scene, camera );
        
        }

        function adjustCamera() {
          console.log('test')

        }

        document.addEventListener('scroll', function(e) { adjustCamera() });



        </script>
  </body>
  <div id="test">

  </div>

  <div id="test2">

    testing121

  </div>

</html>

Do React child components always need to be stateful?

When a child component’s sole purpose is to consume its parent’s state, does it need to be stateful itself?

Looking at these two examples:

“Stateless”

const ServicesCard = ({ service, onClick, isPro = false }) => {
  const name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
  let price = isPro && service.pro?._id ? service.pro.total : service.total;

  // Special case scenarios
  let prefix;
  let suffix;

  if (service.hasPages) {
    prefix = 'from';
  }
  if (service.uid === 'abcdef') {
    prefix = '';
    price = `${price} per page`;
    suffix = '($5 minimum)';
  }
  if (service.uid === 'qwerty') {
    suffix = "+ gov't fees";
  }

  return (
    <div className={styles.servicesCard} onClick={onClick}>
      <h1 className={styles.header}>{name}</h1>
      <p className={styles.pricing}>
        <span className={styles.prefix}>{prefix}</span>
        <span className={styles.price}>{`$${price}`}</span>
        <span className={styles.suffix}>{suffix}</span>
      </p>
    </div>
  );
};

Stateful

const ServicesCard = ({ service, onClick, isPro = false }) => {
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [prefix, setPrefix] = useState('');
  const [suffix, setSuffix] = useState('');

  useEffect(() => {
    const _name = isPro && service.pro?._id ? service.pro.pro_name : service.name;
    let _price = isPro && service.pro?._id ? service.pro.total : service.total;

    // Special case scenarios
    let _prefix;
    let _suffix;

    if (service.hasPages) {
      _prefix = 'from';
    }
    if (service.uid === 'abcdef') {
      _prefix = '';
      _price = `${_price} per page`;
      _suffix = '($5 minimum)';
    }
    if (service.uid === 'qwerty') {
      _suffix = "+ gov't fees";
    }

    setName(_name)
    setPrice(_price)
    setPrefix(_prefix)
    setSuffix(_suffix)
  }, [service]);

  return (
    <div className={styles.servicesCard} onClick={onClick}>
      <h1 className={styles.header}>{name}</h1>
      <p className={styles.pricing}>
        <span className={styles.prefix}>{prefix}</span>
        <span className={styles.price}>{`$${price}`}</span>
        <span className={styles.suffix}>{suffix}</span>
      </p>
    </div>
  );
};

I feel like both of them would behave the same, since a re-render will be triggered by a state change higher up in the tree anyways, forcing everything to be recalculated. React also emphasizes that Data flows down.

Provided that service is the only prop that changes, why should I use more browser memory by using the useState & useEffect React APIs?

How do I solve JavaScript execution error in Johnny-five?

Original post: How do I fix johnny 5 installation error?

When I run my JS file I get this error:

1637373588955 Available COM3 
1637373588956 Connected COM3 
1637373592592 Repl Initialized 
>> 1637373598958 Device or Firmware Error A timeout occurred while connecting to the Board. 

Please check that you've properly flashed the board with the correct firmware.
See: https://github.com/rwaldron/johnny-five/wiki/Getting-Started#trouble-shooting

If connecting to a Leonardo or Leonardo clone, press the 'Reset' button on the board, wait approximately 11 seconds for complete reset, then run your program again. 
events.js:306
    throw err; // Unhandled 'error' event
    ^

I’ve already tried installing different Firmata software but it isn’t helping. What do you think?

Do styles components use JSX?

I am learning to use react and styled components. While using the styled components package to create a button element, the React import at the top of my code editor gives a warning that react is defined/declared but never used.

Isn’t creating a html button and assigning it to a javascript variable JSX ?
Do styled components already have the JSX logic built in ?
Kindly help clear this doubt.
Thanks.

import React from 'react';
import styled from 'styled-components';

const Button = styled.button`
  font: inherit;
  padding: 0.5rem 1.5rem;
  border: 1px solid #8b005d;
  color: white;
  background: #8b005d;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.26);
  cursor: pointer;

&:focus {
  outline: none;
}

&:hover,
&:active {
  background: #ac0e77;
  border-color: #ac0e77;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.26);
}
`

export default Button;