Cannot POST /Auth/signup

im following JavaScript Mastery tutorial for Full Stack Realtime Chat Messaging App with Authentication (https://www.youtube.com/watch?v=MJzbJQLGehs)

and when i try to sign up or sign in i get this error

Cannot POST /Auth/signup

this is my sever>index.js

const express = require('express');
const cors = require('cors');

const authRoutes = require("./routes/auth.js");

const app = express();
const PORT = process.env.PORT || 3000;

require('dotenv').config();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded());

app.get('/',(req,res) => {
    res.send('hello,world!');
});

app.use('/auth', authRoutes);

app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

routes>auth.js

const express = require('express');


const { signup, login } = require('../controllers/auth.js');

const router = express.Router();

router.post('/signup', signup);
router.post('/login', login);

module.exports = router;

and controllers>auth.js

auth.js1 auth.js2

How do I access the “checked” property of a HTML checkbox element using TypeScript?

I have the following HTML Code:

<input type="checkbox" id="check-one">

The following CSS code:

.check-one {
accent-color: #9d3039; }

And the following TypeScript code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  arrayName = new Array(10000);
}

const checkInput = document.getElementById('check-one') as HTMLInputElement;

console.log(checkInput.checked);

Whenever I view the console, all I get is an error that reads: Uncaught TypeError: checkInput is null

I’m wondering why this is happening? Why is it not returning either True or False since checkInput.checked is a boolean? Additionally, how to I manipulate this property so that the box can be checked and unchecked using a line of code in Typescript?

How to create the action of javascript:alert(‘Form Submitted’), which will simply alert that the form was submitted?

I am new to coding. My project requires me to make the contact form have an action of a javascript:alert(‘Form Submitted’), which will simply alert that the form was submitted.
This is my code:

<div class="contact-box">
    <h1>Contact Us</h1>
    <form>
    
        <input type="name" class="input-field" placeholder="Your Name">
        <input type="email" class="input-field" placeholder="Your Email">
        <input type="subject" class="input-field" placeholder="Subject">
        <textarea type="text" class="input-field textarea-field"
        placeholder="Your message"></textarea>

<input type="submit" value="Send Message">


</div>

(JavaScript) Clarification on how asynchronous functions queue with each other [duplicate]

I’m very new to JavaScript, please bear with me if this is quite obvious.

I was watching this video about the event queue and I wrote this code segment to try and see if I understood how JavaScript queues asynchronous functions into their section (I’m not sure what it’s called. In the video, it called it a webapi).

setTimeout( () => console.log('hello'), 5000);
setTimeout( () => console.log('123'), 5000);

From my understanding, the first line of code gets sent off to a separate thread where it starts to get evaluated. Then, the second line of code gets sent off to another thread (different from the first) to get evaluated. As each of these evaluations complete in their own separate threads, they will eventually call their callback function, adding it to the task queue, where the event loop will push them back into the main stack.

I’m hoping someone can confirm or correct me on this, and would appreciate any further reading to help solidify this idea. I have to admit, when I first started reading about asynch functions, I was puzzled since I thought JavaScript was single threaded (so how could it yield any benefits?). I know, foolish.

Using ES6 module in Angular application : Module not found

I have a JavaScript library I’m trying use within an Angular 8 application. The JS library written with ES6 syntax and exports itself as a module. I hosted the bundled module on a local dev server at port 8080.

import widgetLib from './lib/widget.js';
export { widgetLib }

Now to import the module, I tried doing it the same way we import a script from CDN

index.html

<script src = "http://localhost.finra.org:8080/widgetLib.min.js" />

Component.ts

declare let widgetLib: any;//

Then tried to use this variable in the component file. The name is same as the export name. This gives me an error :

Uncaught (in promise) ReferenceError: widgetLib is not defined

When I import moment library using a cdn link in a similar way, it works fine. But hosting my module locally and importing it doesnt work. Can someone help me with this, I feel like I’m doing something wrong while exporting the module

React – Updating State From a Child Component, Then Doing Something Based on State

New to React hooks and state, trying to figure out why my code isn’t working.

I have an App.js file and a child component called Menu.js. Essentially, Menu.js contains a menu that I want to show if a variable called isOpen is true, and hide if isOpen is false. I have added the function at the parent level on App.js, as I have another component that needs to be able to update the state of isOpen as well, but that component is not relevant to my question. Here is the relevant code:

App.js:

import Menu from "./components/Menu";
import { useState } from "react";

export default function App() {
  const [isOpen, setIsOpen] = useState(false);
  const toggleState = () => setIsOpen(!isOpen);
  console.log(isOpen); 
    // This will console log either true or false

  const menuBtn = document.querySelector(".hamburgermenu");
  const mobileMenu = document.querySelector(".mobilemenu");
    // These are elements on the child component, Menu.js

  if (isOpen) {
    menuBtn.classList.add("open");
    mobileMenu.style.zIndex = "5";
      // This should reveal the menu if the value of isOpen is true
  } else {
      menuBtn.classList.remove("open");
      mobileMenu.style.zIndex = "0";
        // This should hide the menu if the value of isOpen is false
  }

return (
  <div>
    <Menu togglestate={toggleState} /> 
      // Passing togglestate down to Menu.js as a prop
  </div>
  );
}

Menu.js:

export default function Menu(props) {
  return (
    <div className="hamburgermenu" onClick={props.togglestate}>
      // Clicking this div will toggle the value of isOpen between true and false
    <div className="mobilemenu">
  );
}

When I try to run that, my whole application breaks and I get the error TypeError: Cannot read properties of null (reading 'classList') at menuBtn.classList.remove("open");

I know that my problem lies in that the default state is false, so it will first try to run the else statement. However, because the class open hasn’t been added to the menuBtn element yet, there is no open class to remove, and it’s erroring out.

I tried to add another nested if/else statement within the original else statement, basically saying that if the element has the class called open, remove it, like this:

  if (isOpen) {
    menuBtn.classList.add("open");
    mobileMenu.style.zIndex = "5";
  } else {
      if (menuBtn.classList.contains("open")) {
        menuBtn.classList.remove("open");
        mobileMenu.style.zIndex = "0";
      } else {
          mobileMenu.style.zIndex = "0";
      }
  }

I also tried moving away from classes entirely and just changing the styles directly as a test, like this:

if (menuOpen) {
  menuBtn.style.display = "block";
  mobileMenu.style.zIndex = "5";
} else {
  menuBtn.style.display = "none";
  mobileMenu.style.zIndex = "0";
}

But I still got an error at the same line, TypeError: Cannot read properties of null (reading 'style') at menuBtn.style.display = "block";

I know this is all a little messy. I’m sure there’s a better way of doing this, but this is how I would go about it with the knowledge that I do have. If there is an easier way, I am open to suggestions!

Attempting to query a TimeStamp from Firestore causes a request loop

Data

I am attempting to query all documents in my collection that are before the current date, but in my emulator log the requests keep looping. What am I doing wrong? Could it be because I have stored the timestamp with a Europe/London timezone?

const ordersRef = firestore.collection('locations/${locationId}/orders').where('dueDate', '<', new Date(Date.now()));
const {
    data: orders,
    status: ordersStatus,
    error: ordersError
} = useFirestoreCollectionData(orders, { idField: 'id' });

Using a ternary expression in React

In this component:

const MovieComponent = (props) => {
  const { Poster, Price, Title } = props.movie;
  return (
    <MovieContainer>
      <CoverImage src={Poster} alt="" />
      <MovieName>{Title}</MovieName>

      <InfoColumn>
        <MovieInfo>FilmWorld: ${Price}</MovieInfo>
        <MovieInfo>CinemaWorld: ${Price}</MovieInfo>
      </InfoColumn>
    </MovieContainer>
  );
};

I’m wanting to write a ternary expression that will change the font color of:

<MovieInfo>FilmWorld: ${Price}</MovieInfo>
        <MovieInfo>CinemaWorld: ${Price}</MovieInfo>

Something basically saying

if (Filmworld Price > CinemaWorld Price) { Filmworld Price = color: "green"}

and vice versa. Although I’m confused as how to do this because they are using the same prop. Is this possible? And would the code be in the movie info section?
This is on React.

How to use Moment.JS to convert to 12 hour clock or 24 hour clock based on timezone

So I’m starting with a REALLY weird format, which is essentially the minutes after midnight represented as a number (in the timezone I’m trying to get to). So if I’m in New York and mean 6:30 AM, the starting value is 390.

Here’s my code so far:

const open_time = (String(startingTime / 60)).split(".") // startingTime of 390 becomes an array of ['6','5']
const open_hour = open_time[0] // open hour becomes '6'
var open_minutes = 0 // if the startingTime was evenly divisible by 60, that means we're on the hour
if (open_time[1] !== undefined) { // startingTime wasn't evenly divisible by 60, need to do some calculations
    open_minutes = Number(`0.${open_time[1]}`) * 60 // get the minutes into the hour
}
const open_minutes_formatted = open_minutes.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
}) // make sure the minutes format in 00 - 09 instead of 0 - 9 for the first 10 minutes of the hour.
const hours = `${open_hour}:${open_minutes_formatted}` // final string outputted

At this point, hours is formatted to something like 6:30, or if it’s in the afternoon, 15:00. My question is, how do I use moment.js to format this time based on the 12 hour clock vs 24 hour clock based on where the user is?

At this point in the code, I’ve used the module tzlookup to get the timezone for where the user is located so I think I can use that, but not sure how the actual conversion looks. Any help appreciated!

Getting error with module not being found in node

Getting error with module not being found in node. I’m using inquirer to collect info in node to generate a read me with that info. I feel like I’m calling the module correctly and it should be working(famous last words) but it gives me an error saying Error: Cannot find module ‘./createMarkdown’. Tried changing the way I’m calling it like just ‘createMarkdown’ and it’s still giving the same error.

// This is the index.js file that im running using node index.js

const readMeLayout = require('./createMarkdown');
const fs = require('fs');
const inquirer = require('inquirer');

const questions = [
    {
        type: 'input',
        name: 'name',
        message: 'What is your name?',
        validate: (value) => {
            if (value) { return true }
            else { return "Name Required" }
        }
    },
    {
        type: 'input',
        name: 'title',
        message: 'What is the title of your project?',
        validate: (value) => {
            if (value) { return true }
            else { return "Title Required" }
        }
    },
    {
        type: 'input',
        name: 'description',
        message: 'What would you describe your project as?',
        validate: (value) => {
            if (value) { return true }
            else { return "Description Required" }
        }
    },
    {
        type: 'input',
        name: 'install',
        message: 'What are your installation instructions?',
    },
    {
        type: 'input',
        name: 'usage',
        message: 'How was your project designed to be used?',
    },
    {
        type: 'input',
        name: 'contributing',
        message: 'How can one contribute to your project?',
    },
    {
        type: 'list',
        name: 'license',
        message: 'Provide license information.',
        choices: ["MIT", "Mozilla_Public", "GNU_Affero General Public Licence v3", "GNU_General Public License v2", "GNU_Lesser General Public License v2.1", "Apache_2.0",]
    },
    {
        type: 'input',
        name: 'github',
        message: 'Enter your GitHub Username.',
        validate: (value) => {
            if (value) { return true }
            else { return "Github required" }
        }
    },
    {
        type: 'input',
        name: 'questions',
        message: 'Enter your email so others can reach you if they have questions.',
    },
];

function writeToFile(fileName, data) {
    fs.writeFile(fileName, data, (err) => {
        if (err) throw err;
    });
    console.log('README created.');
}

function init() {
    inquirer.prompt(questions)
        .then((answers => {
            const readme = readMeLayout(answers);
            writeToFile("README.md", readme);
        }));
}

init();

// this is the module for the layout of the readme file

const readMeLayout = data => {
  const { title, description, usage, installation, license, contributing, name, github, email } = data;
  return `
  # ${title}
  -------------------

  ## Table of Contents  
  ----------------------
  - [Description](#description) 
  - [Usage](#usage)  
  - [Installation](#installation)  
  - [License](#license)  
  - [Contributing](#contributing)  
  - [Questions](#questions)  
    

  ### Description  
  -------------------
  ${description}

  ### Usage  
  ------------
  ${usage}
 
  ### Installation  
  -------------------
  ${installation}

  ### License
  --------------
  ![${license}](https://img.shields.io/badge/license-${license}-blue)

  ### Contributing 
  ------------------

  ### Contact Information
  -------------------------
  ### Github: [${name}](https://github.com/${github})
  #### Email: ${email}
`;
}

module.exports = readMeLayout; 

Javascript check if array contains new object

Hello Im having this weird issue

Basically I connected a js app to a mongodb server
inorder to allow for collect cross referencing
I store the new ObjectId in an array

like this

[
  new ObjectId("62702f1e6b5b6ceaaa94b15b"),
  new ObjectId("62702f1e6b5b6ceaaa94b15b")
]

Now I wanna get another item from the DB and check if its id is contained in the database

console.log(result[0].items.includes(otherres._id))

However it is returned as false even tho it should be true

Can anyone help me with this ?

changeTab Function with jquery

Hi there community i managed to create that code that works as tabs function. Every tab has a collection that change with click on other tab, every collection if has more than 4 products it shows some button like “see all”. I need to add that on the function changeTab. Here is the code i create;

tabs = document.querySelectorAll(".featured-products-section__tab");
tabContents = document.querySelectorAll(".featured-products-section__products");
tabViewAll = document.querySelectorAll(".featured-products-section__view-all");

tabs.forEach(function (tab) {
  tab.addEventListener("click", function () {

    contentId = this.dataset.contentId;
    content = document.getElementById(contentId);

    tabContents.forEach(function (content) {
      content.classList.remove("active");
    });

    tabs.forEach(function (tab) {
      tab.classList.remove("active");
    });

    this.classList.add("active");
    content.classList.add("active");
  });
});
.featured-products-section__view-all.active {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    justify-content: center;
}

.featured-products-section__view-all {
    display: none;
}

I create a new var called tabViewAll to get that button, but where i have to add it?
i tried some ways but unfortunatly no one worked.

Require.js Module name * has not been loaded yet for context

https://github.com/vankasteelj/torrent-tracker-health

I have followed the installation steps, however it is unclear to me how to use that library for my needs.

I ended up using require.js, but had no luck..

At the end, I would need to input these variables which are now displayed in console.log to MySQL database. I can do that myself if this error didn’t prevent me:

Errors

Uncaught Error: Module name "torrent-tracker-health" has not been loaded yet for context: _. Use require([])

index.php

<!DOCTYPE html>
<html lang="en">
  <head>
    <script data-main="scripts/app" src="scripts/require.js"></script>
  </head>
    <body>
      
      <script>
        var torrentHealth = require('torrent-tracker-health');
        var magnet = 'magnet:?xt=urn:btih:9A7290F4021048D2C176A84828E441FCB5400FB1&dn=charlie+chaplin+15+short+films+1914+1917+dvdrip&tr=udp://tracker.coppersurfer.tk:6969/announce&tr=udp://glotorrents.pw:6969/announce&tr=udp://tracker.openbittorrent.com:80/announce';

        torrentHealth(magnet).then(function (res) {
            console.log('seeds:', res.seeds);
            console.log('peers:', res.peers);
            console.log('ratio:', +(Math.round((res.peers > 0 ? res.seeds / res.peers : res.seeds) +'e+2') + 'e-2'));
        }).catch(function (err) {
            console.log('error:', err);
        });
      </script>
    </body>
</html>

Calling a Typescript React method with React.FCarguments

I have a small issue, I’m not able to call a React method because of the way the arguments are passed, I’m not sure I understand the concept. Here is the method with the corresponding props types:

interface Props {
children: (send: OnSend) => React.ReactNode }

type OnSend = (to: string, amount: number) => void

const Send: React.FC = ({ children }) => { //content }

Thanks for helping me with how to call the Send() method when clicking on a button for example.

how to fetch data from mock api in react?

I am using https://www.npmjs.com/package/axios-mock-adapter to fetch mock response .but I am not able to get mock response.

here is my code
https://codesandbox.io/s/frosty-surf-g9tezx?file=/src/App.js

here I am fetching actual data

React.useEffect(() => {
    const a = async function () {
      const ab = await axios.get(
        "https://jsonplaceholder.typicode.com/todos/1"
      );
      console.log(ab);
    };
    a();
  }, []);

using axios adaptor I mock API

/

/ This sets the mock adapter on the default instance
var mock = new MockAdapter(axios);

// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet("https://jsonplaceholder.typicode.com/todos/1").reply(200, {
  users: [{ id: 1, name: "John Smith" }]
});

I need instead of actual request it will get mock response or in other words I can toggle my option sometimes it goes to actual request or some time it goes from mock api