syntax error showing while using express js with vscode [closed]

So I am following a tutorial about APIs and in the very first steps i got stuck

so my code is :

const PORT = 8000;
const express = require("express");
const axios = require("axios");
const cheerio = require("cheerio");

const app = express();

app.get(
  "/",
  (
    req: Request<P, XMLHttpRequestBodyInit, ResQuery, Locals>,
    res: Response<ResBody, Locals>
  ) => {
    res.json("welcome to my api");
  }
);

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

I am getting this error and i don’t really know why

the error i am getting:

req: Request<P, XMLHttpRequestBodyInit, ResQuery, Locals>,
^
SyntaxError: Unexpected token ‘:’

I have already searched for an answer and got a solution that didn’t work for me

which suggested that I should disable the builtin TypeScript and JavaScript Language Features in vs code and to download and enable flow language support extension

I tried that but still got the same error

Am I missing some extensions or certain packages ?

How do I make a cell item of a table row bold for n seconds?

I have a piece of code where I am calling my server to fetch some values and update the table if that value isn’t present there. After the updation, I want the user to be notified of the row where the value was updated, by making it’s cell value bold for n seconds.

var table=document.getElementById("employee_details");

var jsonString = JSON.stringify(array);

$.ajax({
    url: '/server.php',
    type: 'POST',
    data: {"input":"calculate_charges",
           data:jsonString},
    cache: false,
    success:function(response){

        const arr3=JSON.parse(response);

        for(var i=0; i<arr3.length; i++){

            if(table.rows[i+1].cells.item(10).innerHTML!=arr3[i][2]){

                 table.rows[i+1].scrollIntoView({
                     behavior: 'smooth',
                     block: 'center'
                 });

                 table.rows[i+1].cells.item(10).innerHTML=arr3[i][2];

                 setTimeout(function(){
                       table.rows[i+1].cells.item(10).style.fontWeight = "500";
                 },7000);

                 setTimeout(function(){
                       table.rows[i+1].cells.item(10).style.fontWeight = "900";
                 },4000);
            }
        }
    }
    complete:function(){}
});

Upon executing the code, I keep getting this error in the console:

Uncaught TypeError: Cannot read properties of undefined (reading
‘cells’)

And the cell item doesn’t get bold. How do I fix this issue?

object not sort based on the value in JavaScript (having key and value number)

Javascript expected object result not getting when sorting on value numbers( and both key and value are also numbers)

let team_id_Point = {
  26: 15,
  32: 1,
  127: 21,
};

function sortObjectbyValue(obj = {}, asc = true) {
  const ret = {};
  Object.keys(obj)
    .sort((a, b) => obj[asc ? a : b] - obj[asc ? b : a])
    .forEach((s) => (ret[s] = obj[s]));
  return JSON.stringify(ret);
}

console.log(sortObjectbyValue(team_id_Point, false));

result from above:

{"26":15,"32":1,"127":21}

required output:

{"127":21,"26":15,"32":1}

how can a logged in user add a number using reactjs

i am building an website about warehouse management system . so, there’s a task that I have to put a number in the input field and there’s a button next to it so after the putting the number I have to click the button and the result will show in quantity items field. but I don’t know how to do it

fetch URL mismatch when using React and Node

I am building a simple client-server app using React for the frontend and Node for the backend. For my client side:

function App() {

  useEffect(() => {
    fetch("/api")
    .then(response => response.json())
    .then(json => {
      console.log(json)
    })
  }, [])

  return (
    <div className="App">
    </div>
  )
}

and my server side:

const express = require("express")
const app = express()

app.get("/api", (req, res) => {
    res.json({"users": ["Alvin", "Ben", "Charlie"]})
    console.log("GET request succeeded")
})

app.listen(5000, () => {console.log("server running on port 5000")})

And I’ve added "proxy": "http://localhost:5000", to my package.json

Now everything works, and I can see the response JSON being printed out. The only thing that I don’t understand is why is my request URL http://localhost:3000/api when I’m actually requesting from http://localhost:5000/api?

enter image description here

MongoDB find() giving wrong object?

I am running a mongo query from the Order database which aims to fetch the orders of a particular user by using his email-id. This is done using an API, but I am getting the complete object with some unnecessary details.

Code

I have written the following API in nextJS name myorders

import Order from "../../models/Order";
import connectDB from "../../middleware/mongoose";
import jsonwebtoken from "jsonwebtoken";

const handler = async(req, res) => {
    const token = req.body.token;
    const data = jsonwebtoken.verify(token,process.env.JWT_SECRET);
    console.log(data)
    let mere_orders = Order.find({email: data.email})
    console.log("mereorders12 = ", mere_orders)
    res.status(200).json({mere_orders});
  }
  

export default connectDB(handler);

And console.log("mereorders12 = ", mere_orders) gives me this

mereorders12 =  Query {
  _mongooseOptions: {},
  _transforms: [],
  _hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
  _executionStack: null,
  mongooseCollection: Collection {
    collection: Collection { s: [Object] },
    Promise: [Function: Promise],
    modelName: 'Order',
    _closed: false,
    opts: {
      autoIndex: true,
      autoCreate: true,
      schemaUserProvidedOptions: [Object],
      capped: false,
      Promise: [Function: Promise],
      '$wasForceClosed': undefined
    },
    name: 'orders',
    collectionName: 'orders',
    conn: NativeConnection {
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: {},
      replica: false,
      options: null,
      otherDbs: [],
      relatedDbs: {},
      states: [Object: null prototype],
      _readyState: 1,
      _closeCalled: undefined,
      _hasOpened: true,
      plugins: [],
      id: 0,
      _queue: [],
      _listening: false,
      _connectionString: 'mongodb://localhost:27017/chesswear',
      _connectionOptions: [Object],
      client: [MongoClient],
      '$initialConnection': [Promise],
      db: [Db],
      host: 'localhost',
      port: 27017,
      name: 'chesswear'
    },
    queue: [],
    buffer: false,
    emitter: EventEmitter {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      [Symbol(kCapture)]: false
    }
  },
  model: Model { Order },
  schema: Schema {
    obj: {
      email: [Object],
      orderId: [Object],
      paymentInfo: [Object],
      products: [Object],
      address: [Object],
      subtotal: [Object],
      status: [Object]
    },
    paths: {
      email: [SchemaString],
      orderId: [SchemaString],
      paymentInfo: [SchemaString],
      products: [Mixed],
      address: [SchemaString],
      subtotal: [SchemaNumber],
      status: [SchemaString],
      _id: [ObjectId],
      updatedAt: [SchemaDate],
      createdAt: [SchemaDate],
      __v: [SchemaNumber]
    },
    aliases: {},
    subpaths: {},
    virtuals: { id: [VirtualType] },
    singleNestedPaths: {},
    nested: {},
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: { initializeTimestamps: [Function (anonymous)] },
    methodOptions: {},
    statics: {},
    tree: {
      email: [Object],
      orderId: [Object],
      paymentInfo: [Object],
      products: [Object],
      address: [Object],
      subtotal: [Object],
      status: [Object],
      _id: [Object],
      updatedAt: [Function: Date],
      createdAt: [Object],
      __v: [Function: Number],
      id: [VirtualType]
    },
    query: {},
    childSchemas: [],
    plugins: [ [Object], [Object], [Object], [Object], [Object] ],
    '$id': 1,
    mapPaths: [],
    s: { hooks: [Kareem] },
    _userProvidedOptions: { timestamps: true },
    options: {
      timestamps: true,
      typeKey: 'type',
      id: true,
      _id: true,
      validateBeforeSave: true,
      read: null,
      shardKey: null,
      discriminatorKey: '__t',
      autoIndex: null,
      minimize: true,
      optimisticConcurrency: false,
      versionKey: '__v',
      capped: false,
      bufferCommands: true,
      strictQuery: true,
      strict: true,
      pluralization: true
    },
    '$timestamps': { createdAt: 'createdAt', updatedAt: 'updatedAt' },
    '$globalPluginsApplied': true,
    _requiredpaths: [ 'status', 'subtotal', 'address', 'products', 'orderId', 'email' ]
  },
  op: 'find',
  options: {},
  _conditions: { email: '[email protected]' },
  _fields: undefined,
  _update: undefined,
  _path: undefined,
  _distinct: undefined,
  _collection: NodeCollection {
    collection: Collection {
      collection: [Collection],
      Promise: [Function: Promise],
      modelName: 'Order',
      _closed: false,
      opts: [Object],
      name: 'orders',
      collectionName: 'orders',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    },
    collectionName: 'orders'
  },
  _traceFunction: undefined,
  '$useProjection': true
}

But I should return order like this

{  
 orders: [
 { 
 
 "_id":"62693ae3f7fd0b7d87c8eb9c"},
 "email":"[email protected]",
 "orderId":"1389629752594",
 "paymentInfo":"No payment info",
 "products":{...},
 "address":"adasdklfasflka",
 "subtotal":4,
 "status":"Paid",
 "createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
 "updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0

}
,
 { 
 
 "_id":"62693ae3f7fd0b7d87c8eb9c"},
 "email":"[email protected]",
 "orderId":"1389629752594",
 "paymentInfo":"No payment info",
 "products":{...},
 "address":"adasdklfasflka",
 "subtotal":14,
 "status":"Paid",
 "createdAt":{"$date":"2022-04-27T12:45:23.352Z"},
 "updatedAt":{"$date":"2022-04-27T12:45:23.352Z"},"__v":0

}

]

}

Additionally this is the model schema of Order

const mongoose = require("mongoose");

const OrderSchema = new mongoose.Schema(
  {
    email: { type: String, required: true },
    orderId: { type: String, required: true },
    paymentInfo: { type: String, default: "No payment info" },
    products: { type: Object, required: true },
    address: { type: String, required: true },
    subtotal: { type: Number, required: true },
    status: { type: String, required: true, default: "Pending" },
  },
  { timestamps: true }
);

export default mongoose.models.Order || mongoose.model("Order", OrderSchema);

Please help ??

TypeError: cardsData.map is not a function

I am supposed to store queries for users in the cardsData and I need to map through the data in cardsData but if I run the code on my terminal i get this error. I am a newbie and I have searched a lot of forums that suggest that cardsData is supposed to be an array but I do not know how to go forward from there. I am just following a youTube tutorial and that was exactly what was done in the tutorial.
it worked on the youTube why can’t it work for me too?

please somebody help.

[enter image description here][1]import { useContext } from 'react'
import { TinderContext } from '../context/TinderContext'
import { SiTinder } from 'react-icons/si'
import CardHeader from './CardHeader'
import CardFooter from './CardFooter'
import TinderCardItem from './TinderCardItem'

const style = {
  wrapper: `h-[45rem] w-[27rem] flex flex-col rounded-lg overflow-hidden`,
  cardMain: `w-full flex-1 relative flex flex-col justify-center items-center bg-gray-500`,
  noMoreWrapper: `flex flex-col justify-center items-center absolute`,
  tinderLogo: `text-5xl text-red-500 mb-4`,
  noMoreText: `text-xl text-white`,
  swipesContainer: `w-full h-full overflow-hidden`,
}

const Card = () => {
  const { cardsData } = useContext(TinderContext)

  return (
    <div className={style.wrapper}>
      <CardHeader />
      <div className={style.cardMain}>
        <div className={style.noMoreWrapper}>
          <SiTinder className={style.tinderLogo} />
          <div className={style.noMoreText}>
            No More Profiles in your Location...
          </div>
        </div>
        <div className={style.swipesContainer}>
          {cardsData.map((card, index) => (
            <TinderCardItem card={card} key={index} />
          ))}
        </div>
      </div>
      <CardFooter />
    </div>
  )
}

export default Card

how to check the guildMember is joined to my guild or others discord.js

At first I created a guildMemberAdd event in my main.js folder:

client.on('guildMemberAdd', guildMember =>{
    let welcomeRole = ('885616406538899517');
    guildMember.roles.add(welcomeRole);
});

I want to check if the guildMember is joined my guild or others.

Notes: I want to use the if statement.

//example:
if(guildMember.guild.id == '847071265100791849'){
let welcomeRole = ('885616406538899517');
    guildMember.roles.add(welcomeRole);
} else return;

I am using discord.js v13 and node.js v16.14.2

want to use getRow inside allRowsValid for sudoku solver how can i solve it?

So i have been trying to write a sudoku solver and i had to complet methods inside an extend class here’s the head of the code:

class Board extends EventEmitter {
  constructor(board) {
    super();

    this.board = board || [
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 0, 0, 0, 0, 0, 0],
    ];
  }

  getRow(index) {
    return this.board[index];
  }

here i have to check if all the rows inside that board are valid (from 1 to 9 no repet):

allrowsValid() {
  for (let c = 0; c < 9; ++c) {
    **var row = this.getRow(c)** ***//what i need to fix***

      for ( let num = 1; num <= 9; ++num){
        if (this.board[row][c] === num) {
          return false;
      }
      }
    }
    return true;
    }

How can i solve it ?
thanks !

How to reduce an array of objects to the required format?

I have a problem with proper grouping of objects in an array.

I have an array in this format:

const places = [
  {
    id: 1,
    name: "p 1",
    icon: "icon-p",
    parent_id: null,
  },
  {
    id: 2,
    name: "p 2",
    icon: "icon-p",
    parent_id: 1,
  },
  {
    id: 3,
    name: "p 3",
    icon: "icon-p",
    parent_id: 1,
  },
  {
    id: 4,
    name: "t 1",
    icon: "icon-t",
    parent_id: null,
  },
  {
    id: 5,
    name: "t 2",
    icon: "icon-t",
    parent_id: 4,
  },
  {
    id: 6,
    name: "t 3",
    icon: "icon-t",
    parent_id: 4,
  },
  {
    id: 7,
    name: "a 1",
    icon: "icon-a",
    parent_id: null,
  },
  {
    id: 8,
    name: "b 1",
    icon: "icon-b",
    parent_id: null,
  },
  {
    id: 9,
    name: "h 1",
    icon: "icon-h",
    parent_id: null,
  },
  {
    id: 11,
    name: "h 2",
    icon: "icon-h",
    parent_id: 9,
  },
  {
    id: 12,
    name: "h 3",
    icon: "icon-h",
    parent_id: 9,
  },
  {
    id: 13,
    name: "h 4",
    icon: "icon-h",
    parent_id: 9,
  },
];


const groupReultsByIcon = places.reduce((r, { icon, ...object }) => {
  let temp = r.find((o) => o.icon === icon);
  if (!temp) r.push((temp = { icon, children: [] }));
  temp.children.push(object);
  return r;
}, []);


groupReultsByIcon.forEach(({ icon, children }) => {
  console.log('icon-name: ', icon);
  console.log('children-array: ', children);
});

The code that I have managed to prepare so far is, unfortunately, only grouping by icon.

I am trying to get such an array:

const newArrayObject = [
  {
    id: 1,
    icon: "icon-p",
    children: [
      {
        id: 1,
        name: "p 1",
        icon: "icon-p",
        parent_id: null,
      },
      {
        id: 2,
        name: "p 2",
        icon: "icon-p",
        parent_id: 1,
      },
      {
        id: 3,
        name: "p 3",
        icon: "icon-p",
        parent_id: 1,
      },
    ],
  },
  {
    id: 4,
    icon: "icon-t",
    children: [
      {
        id: 4,
        name: "t 1",
        icon: "icon-t",
        parent_id: null,
      },
      {
        id: 5,
        name: "t 2",
        icon: "icon-t",
        parent_id: 4,
      },
      {
        id: 6,
        name: "t 3",
        icon: "icon-t",
        parent_id: 4,
      },
    ],
  },
  {
    id: 7,
    icon: "icon-a",
    children: [
      {
        id: 7,
        name: "a 1",
        icon: "icon-a",
        parent_id: null,
      },
    ],
  },
  {
    id: 8,
    icon: "icon-b",
    children: [
      {
        id: 8,
        name: "b 1",
        icon: "icon-b",
        parent_id: null,
      },
    ],
  },
  {
    id: 9,
    icon: "icon-h",
    children: [
      {
        id: 9,
        name: "h 1",
        icon: "icon-h",
        parent_id: null,
      },
      {
        id: 11,
        name: "h 2",
        icon: "icon-h",
        parent_id: 9,
      },
      {
        id: 12,
        name: "h 3",
        icon: "icon-h",
        parent_id: 9,
      },
      {
        id: 13,
        name: "h 4",
        icon: "icon-h",
        parent_id: 9,
      },
    ],
  },
];

As you can see grouping should follow parent_id and id
An object that parent_id === null should have children and in it itself as well as objects with its id.

Need help to insert price based on checkbox checked

I have a form where I calculate the price based on the checkboxes checked. But I am having trouble as its not updating the final price correctly. I did some jquery coding but its not functioning properly. Please someone help me debug the code and help me fix it.

//Price Calculator
$(document).ready(function(){
  
  function Calculator(){
    let totalAmount = 0;
    if($('input[datasource=service_0]').is(':checked')){  // First Checkbox targeted using datasource attribute
      totalAmount = 395;
      return totalAmount;
    }else if($('input[datasource=service_1]').is(':checked')){   // First Checkbox targeted using datasource attribute
      totalAmount = 392;
      return totalAmount;
    }else if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2) {
      totalAmount = 397;
      return totalAmount;
    }
  }
  //Insert Updated Amount to Budget field
  $("input[type=checkbox]").on("click", function(){
    if ($("input[datasource=service_0]:checked,input[datasource=service_1]:checked").length == 2){
      $("input[name=wpcf-book-amount]").val(Calculator());
    } else{
      $("input[name=wpcf-book-amount]").val(Calculator());
    }
  })
  
})

Form containing the fields responsible to calculate the booking amount

how to count number of replaced strings in javascript

How do I properly count the amount of replaced strings in Javascript. my increment function is in the replacement part of replace function bellow gives me a “0”.

function newrep() {
  var fid = document.getElementById('find').value;
  var regexp = new RegExp(fid, "gi");

  var rv = document.getElementById('replace').value;
 
  var inp = document.getElementById('message').value;

 let str2=(inp.replace(regexp,rv,function(x){count+=1;return"1"}))

  document.getElementById("message").value = str2;
  document.getElementById("ChCtr").innerHTML = count;

}
<main/> Message:
<br />
<textarea id="message" name="message" rows="3" cols="20">Hello </textarea>
<span id="ChCtr"></span> //display here
<br/><br/> Find:


<br />
<input type="text" id="find" name="find" size="30"><br />

<br/><br/> Replace:


<br />
<input type="text" id="replace" name="replace" size="30"><br />
<br/><br/>


<button onclick="newrep()">Find and Replace</button>
<br/><br/>
</main>

Where to put builded nodejs application on my apache2 server

I am building project which I want to deploy on my own static ip server (apache2). I am using postgresql database and python api (want to use it just as API not frontend), currently I am making frontend where I need to use node packages because I need to download and install OpenLayers for usage with OSM maps, when I build nodejs project I get dist/ directory which I need to put to production. I would like to know if it means that I can just put it to /var/www/html directory and if no please where should put it? Or please some explanation how it works 🙂 Thank you very much.

Why javascrpt does not select the button?

I am creating with javascript that when I select the like button it prints Hi.
I don’t understand why when inspecting it is not selecting the button.
I don’t understand what I’m doing wrong.
Can it be that I do not get the javascript url?

index.hmtl

<script src="{% static 'network/index.js' %}"></script>
<form method="post">{%csrf_token%}
        <button onclick="darLike()">Like</button>
        <a id="resultado"></a>
        <svg xmlns="http://www.w3.org/2000/svg" width="16 " height="16 " fill="currentColor " class="bi bi-heart " viewBox="0 0 16 16 ">
            <path d="m8 2.748-.717-.737C5.6.281 2.514.878 1.4 3.053c-.523 1.023-.641 2.5.314 4.385.92 1.815 2.834 3.989 6.286 6.357 3.452-2.368 5.365-4.542 6.286-6.357.955-1.886.838-3.362.314-4.385C13.486.878 10.4.28 8.717 2.01L8 2.748zM8 15C-7.333
            4.868 3.279-3.04 7.824 1.143c.06.055.119.112.176.171a3.12 3.12 0 0 1 .176-.17C12.72-3.042 23.333 4.867 8 15z "/>
        </svg>
    </form>

index.js

document.addEventListener('DOMContentLoaded', function() {
    document.addEventListener('click', () => function darLike() {
        const contenido = document.querySelector('#resultado')
        fetch(`like/${post.id}`, {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrftoken
                }
            })
            // Put response into json form
            .then(response => response.json())
            .then(data => {
                console.log(data);
                contenido.innerHTML = "Hi"
            })
            // Catch any errors and log them to the console
            .catch(error => {
                console.log('Error:', error);
            });
    });
    // Prevent default submission
    return false;
})

TUI Calendar – Preventing Overlapping Schedules

I’m using TUI Calendar as a scheduler and all works as expected up until trying to prevent schedules from overlapping. There doesn’t seem to be a config item for this like on FullCalendar which uses slotEventOverlap: false,.

I was wondering if anyone has come into this problem and has resolved it another way as I don’t think TUI Calendar has a similar config item?

I have tried using the beforeCreateSchedule event to compare against other schedule items but can’t seem to gain access to the other schedules on the calendar.