blocked by CORS policy Method PATCH is not allowed

im tryng build crud app using MERN stack,
method add and get not got blocked by cors,
but patch method got blocked by cors
alredy install cors module on my server
and still didnt work

routes

import express from 'express';
import { createPost, getPost, updatePost } from '../controllers/posts.js';

const router = express.Router();

router.get('/', getPost);
router.post('/', createPost);
router.patch('/:id', updatePost);

export default router;


server/controllers

export const updatePost = async (req, res) => {
  const { id: _id } = req.params;
  const post = req.body;
  if (!mongoose.Types.ObjectId.isValid(id))
    return res.status(404).send(`no post with id ${id}`);
  const updatedPost = postMessage.findByIdAndUpdate(_id, post, { new: true });
  res.json(updatedPost);
};


client>src>api
import axios from 'axios';

const url = 'http://localhost:3001/posts';

export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatePost) =>
  axios.patch(`${url}/${id}`, updatePost);

How to fill in missing months of last year in an array using javascript

I have an array of months and its count as follows:

[
            {
                "registered_to_month": "04-2022",
                "count": "3"
            },
            {
                "registered_to_month": "03-2022",
                "count": "4"
            },
            {
                "registered_to_month": "02-2022",
                "count": "6"
            },
            {
                "registered_to_month": "01-2022",
                "count": "6"
            },
            {
                "registered_to_month": "11-2021",
                "count": "11"
            }
        ]

This result I am getting last 12 months The months which is not available I want to replace with 0 so that I can plot in the graph. I am not able to figure out how can I solve this.

variable scope for require

I have a limited JS interpreter for a mobile app, which does not allow usage of module.export. It has some custom global variables, say, customProp which are available at runtime, in the interpreter, in the app.

For my tests though I still need to require such JS files and define such variables. Is there a way to pass a mocked value to such custom variables during tests, when call them using require? A straightforward way would be just to add such variables to the global scope, but with many tests it becomes unusable and very error prone.

A typical script script.js:

customProp.customFuncCall(); // This works in the engine

A test test.js:

const { script } = require("./script"); // <- This throws an error: customProp is undefined

I see it is possible to pass a variable to a module when require it, but in that case, the module has to have
module.exports = function (passedVariable) {} which I cannot do.

ReactJS: How to clear state values from useLocation after page reload

I have this scenario, I have a create page, when user is done from create page it will automatically navigate to list page, in my create page I have set some state values the will be used in list page. From that point everything is working fine. But when I try to reload the list page, the state values is still there but when I try to navigate to other pages and go back to list page the state values is cleared, how can I make state values clear when list page is reloaded after setting state values from create page?

Create Page code:

import { Link, useNavigate } from "react-router-dom";

const CreatePage = () => {
const navigate = useNavigate();
const handleSubmit = async (e: any) => {
//some code here
if (res.status === 201) {
              navigate("/post", {
                state: {
                  status: true,
                  message: "Post successfully created.",
                },
                replace: true,
              });
            }

});

};

List Page code:

import { Link, useLocation } from "react-router-dom";
    interface LocationState {
      status: boolean;
      message: string;
    }
    
    const ListPage = () => {
      const location = useLocation();
      const state = location.state as LocationState;
    
    return(
    //some html here
    <Col>
              {state?.status && <ToastNotificationBasic message={state?.message} />}
            </Col>
    );
    };

And because of that, the toast message always showing everytime list page is reload. What am i missinge here? Thank you!

Form Submit Not Redirecting

I’m setting up a test e-commerce site and the setup is nearly complete. I’m implementing custom Bitcoin Payment at the checkout but can’t figure out why the submit button isn’t submitting + redirecting. Basically you go through checkout (you can put in dummy data) and then a button comes up that says “Pay with Bitcoin” but the thing isn’t redirecting me to another page (the page redirect is the expected behaviour upon form submission).

The store link is: https://ibex-swag-store-front.herokuapp.com/checkout

Here’s the component:

  return (
    <div className="flex flex-col">
      <form 
        class="ibexpay-container justify-content-center align-self-center"
        action="https://ventas.ibexmercado.com/ibexpay_ecommerce/api/v1/buttons/create" 
        method="post"
        target="_top"
      >
        <input type="hidden" name="button_id" value="U8gxqShiGtS5Xp8yCihUST" />
        <input type="hidden" name="description" value="(IBEX E-Shop) shop transaction." />
        {/* <input type="hidden" name="amount" v-model="cartValueUsd" /> */}
        <center>
          <ibexpay-button button-id="U8gxqShiGtS5Xp8yCihUST" description="Custom Memo" amount="0.05" />
        </center>
      </form>
    </div>
  )
}

export default ManualPayment

Any help figuring this out would be appreciated!

How to integrate WebcamCapture with another element in React

I’m Trying To Add a background color to my webcam project
But when I add
<WebcamCapture /> with

<div
    style={{ backgroundColor: bgcolor, width: "100vw", height: "100vh" }}
    className="App"> it get an error, 

but when I run each one separately it runs (either background becomes blue or the camera without the blue background, I want to have both)

import React, { useState } from 'react';
    

import './App.css';

import WebcamCapture from './Webcam/webcam'

//import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

//import Home from './pages/pagesindex';
//import SigninPage from './pages/signin';








function App() {
  var colors = [
    {
      value: 1,
      label: "blue"
    
    }
  ];
  var [inputValue, setInputValue] = useState(colors[0].label);
  var [bgcolor, setbgColor] = useState(colors[0].label);
  
  return (

     <WebcamCapture />

   <div
    style={{ backgroundColor: bgcolor, width: "100vw", height: "100vh" }}
    className="App"
  >
   
  </div>
   


    
   
  );
}

export default App;

This is how I want it look like

How it Should look Like

Cannot set Object value to passed value: InventoryItem.js:7 Uncaught TypeError: Cannot set properties of undefined (setting ‘itemName’)

I am trying to pass the value from 3 TextInput’s to a constructor on a button press. The values themselves are passing fine, I can verify that when I console.log() them. But the object property itself is having a type error thrown while I’m trying to set it’s value, which doesn’t make much sense to me. I’m inexperienced with JavaScript, but I’ve never seen a type error on something I’m trying to set the value of.

“Uncaught TypeError: Cannot set properties of undefined (setting ‘itemName’) at InventoryItem (InventoryItem.js:7:1)”

Taking the text Input:

const AddItem = props => {

  const [itemName, setName] = useState('');
  const [ExpirationDate, setExp] = useState('');
  const [ReminderDate, setRem] = useState('');

    return(
    <View style={styles.header}>
      <TextInput
        style = {styles.input}
        placeholder = "Enter Item Name"
        onChangeText={(val) => setName(val)}/>

      <TextInput
        style = {styles.input}
        placeholder = "Enter Expiration Date (mm/dd/yyyy)"
        onChangeText={(val) => setExp(val)}/>

      <TextInput
        style = {styles.input}
        placeholder = "Enter Reminder Date (mm/dd/yyyy)"
        onChangeText={(val) => setRem(val)}/>

      <Text>Name: {itemName}, Expiration: {ExpirationDate}, Reminder: {ReminderDate}</Text>

      <TouchableOpacity style={styles.btn} onPress={() => InventoryItem(itemName, ExpirationDate, ReminderDate)}>
        <Text style={styles.btnText}> <Icon name="plus" size={20}/>Add Item</Text>
      </TouchableOpacity>

      <TouchableOpacity style={styles.btn} onPress={() => props.navigation.navigate('Home')}>
        <Text style={styles.btnText}>Return Home</Text>
      </TouchableOpacity>
    </View>
  )
}

Constructor:

export function InventoryItem(name, ExpirationDate, ReminderDate) {
    console.log("Here");
    console.log(name)
    console.log(ExpirationDate)
    console.log(ReminderDate)

    this.itemName = name;
    this.ExpirationDate = ExpirationDate;
    this.ReminderDate = ReminderDate;

    console.log(this.itemName);
    console.log(this.ExpirationDate);
    console.log(this.ReminderDate);
}

Console Log

I was initially casting the parameters themselves to strings, and trying other things like that before this.itemName = name and such, then I realized it wasn’t the passed values that are the problem, but “this.itemName = ” itself thats having the type error. And I’m not sure what to do with that.

print the output by clicking the + button (with js)

How to print any number of these inputs by clicking the + button?
(with the help of javascript)

     <div class="mb-3">
     <label for="exampleFormControlTextarea1" class="form-label">options</label>
     <ul id="my_list">
         <div class="input-group mb-3">
             <div class="input-group-text">
                 <input class="form-check-input mt-0" type="checkbox">
             </div>
             <input type="text" class="form-control">
         </div>
     </ul>

    <button type="button" class="mt-3" id="btn_p" onclick="child_new()" >+</button>

regex that captures optional property in style attribute

I have the following 2 strings:

<span id="1-1" role="presentation" dir="ltr" style="left: 72px; top: 87.8641px; font-size: 11px; font-family: sans-serif; transform: scaleX(0.999349);">&lt;span&gt;&lt;/span&gt;</span>
<span id="1-2" role="presentation" dir="ltr" style="left: 72px; top: 102.41px; font-size: 11px; font-family: sans-serif;">&lt;div&gt;&lt;/div&gt;</span>

I have a regex that captures the left and top values in the style attribute.
However, there is also a transform property that is optional, and I’d like to capture it if it exists.

Here’s what I came up with:

<span id="1-[1|2]".*?left:s(.*?)px.*?top:s(.*?)px.+?(transform:sscaleX((.*)))?.+?(?=">)

However, the value inside of scaleX(...) is not being captured.
Any thoughts on what to do?

Four fails after testinmg get all book scenario

I have to test my bookshelf-api back-end in get all scenario. I want to get my all books with :

  1. status code 200 as successful status
  2. sorting by name, reading, and finish query

My handler file on handler.js with filter function on filter.js

    pm.response.to.have.status(200);
});

pm.test('response header Content-Type should be application/json', () => {
    pm.expect(pm.response.headers.get('Content-Type')).to.equals('application/json; charset=utf-8');
});

pm.test('response body should be an object', () => {
    const responseJson = pm.response.json();
    pm.expect(responseJson).to.be.an('object');
});

pm.test('response body object should have correct property and value', () => {
    const responsJson = pm.response.json();

    pm.expect(responsJson).to.haveOwnProperty('status');
    pm.expect(responsJson).to.haveOwnProperty('data');

    pm.expect(responsJson.status).to.equals('success');
    pm.expect(responsJson.data).to.be.an('object');
});

pm.test('response body data object should have a array books and contains one items', () => {
    const responseJson = pm.response.json();
    const { data } = responseJson;

    pm.expect(data).to.haveOwnProperty('books');
    pm.expect(data.books).to.be.an('array');
    pm.expect(data.books).to.lengthOf(1);
});

pm.test('the books should have contains only id, name, and publisher property', () => {
    const responseJson = pm.response.json();
    const { data: { books } } = responseJson;

    books.forEach((book) => {
        pm.expect(Object.keys(book)).to.lengthOf(3);
        pm.expect(book).to.haveOwnProperty('id');
        pm.expect(book).to.haveOwnProperty('name');
        pm.expect(book).to.haveOwnProperty('publisher');
    });
});```


But i had 4 fails
[![enter image description here][1]][1]
And this is my repository
https://github.com/faqirilmu31/bookshelf-api
Please anyone could help me?


  [1]: https://i.stack.imgur.com/McQkO.png

Assign Nested map unique key, javascrpit

I need to assign assign each input their own id.

const sep = words.map((word, ind) => {
  return (
     <div key={ind} className="guess__word">
       {word.split("").map((letter, id) => {
         if (letter === " ") {
           return <SpaceBox key={id} letter={letter} />;
         } else {
           return <LetterBox key={id} id={id} letter={letter} />;
         }
      })}
     </div>
   );
 });

The problem that I am having is that due to the map being nested, the value of id keeps reseting back to 0. Each word of words has a different length so if kinda hard to figure out if there is a math equation that would help me solve this.

for reference, the length of each word is 10, 3, 4, and 4.

Also I need the ids to equal up to the length of words. So I would need the ids to be 0-20.

Class element isn’t identified?

I’m new to html/css/js and i am trying to make a open and close cart for my pretend ecommerce website. The problem is when cart icon is onclick, it doesn’t open so I think it isn’t declared properly. I was following a tutorial on this until this part, I can’t figure out why.

Here’s the html:

        <div class="header">
        <div class="navbar">
        <div class="logo">
            <a href="/index.html"><h1>Homeflix</h1></a>
        </div>
        <nav>
            <ul>
                <li><a href="/shop.html">Shop</a></li>
                <li><a href="">About Us</a></li>
                <li><a href="">Support</a></li>
                <li><img src="/img/cart.png" width="20px" height="20px" id="cart-icon"></li>
            </ul>
        </nav>
        <!--Cart-->
        <div class="cart">
            <h2 class="cart-title">Your Cart</h2>
            <!--Cart Content-->
            <div class="cart-content">
                <div class="cart-box">
                    <img src="/img/smnwh.jpg" alt="" class="cart-img">
                    <div class="detail-box">
                        <div class="cart-product-title">Spider-man No Way Home</div>
                        <div class="cart-price">$75.00</div>
                        <input type="number" value="1" class="cart-quantity">
                    </div>
                    <!--Remove Cart-->
                    <i class="fa-solid fa-trash-can cart-remove"></i>
                </div>
                <!--Total-->
                <div class="total">
                    <div class="total-title">Total</div>
                    <div class="total-price">$0</div>
                </div>
                <!--Buy Button-->
                <button type="button" class="btn-buy">Buy Now</button>
                <!--Cart Close-->
                <i class="fa-solid fa-xmark" id="close-cart"></i>
            </div>
        </div>
    </div>

Here’s my CSS:

.cart {
    position:fixed;
    top: 0;
    right:-100%;
    width:360px;
    min-height: 100vh;
    padding: 20px;
    background: var(--bg-color);
    box-shadow: -2px 0 4px hsl(0 4% 15% / 10%);
    transition: 0.3s;
}
.cart:active {
    right:0;
}

And here’s my JS:

let cartIcon = document.querySelector("#cart-icon");
let cart = document.querySelector(".cart");
let closeCart = document.querySelector("#close-cart");



cartIcon.onclick = () => {
    console.log("pass");
    cart.classList.add("active");
}
closeCart.onclick = () => {
    console.log("close");
    cart.classList.remove("active");
}