Adding new endpoints for test purposes

Lets say that I have an example in which:…
I have only one account – admin by default
I need to change user permissions – to non-admin one.
I believe that I have few options available (not great yet can be used)
First – Create a new endpoint on a server just for testing – to make it possible for non-admin user to update those permissions. This idea seems pretty odd to me to change something like that.
Second – have multiple users to be able to switch between them for different roles (all in all not that simple for now)
Third – Connect to db and make those changes on db – probably easiest option

What’s your opinion? Would you suggest some best practices?
Any ideas much appreciated

Update value from a state array if > 1

I have a cart array. It stores my products, and, when I add the same item that already exists on the array, it only increases the quantity. It is like this(values only for example):

favs = [{
  key: id
  name: 'Product Name'
  value: 555
  quantity: 4
}, ]

I am creating a ‘remove from cart’ button. If I use slice, the whole object is deleted. So I’ve created the following function:

 const [favs, setFavs] = useState([])
 const { id } = useParams()
 const handleRemove = (index) => {
    if (cart[id].quantity > 1) {
      *some function here* <-
    } else {
    setCart([
        ...cart.slice(0, index),
        ...cart.slice(index+1)
    ])
    console.log('removeu')
  }}

What should I put inside the “if” to return quantity– ? I’ve thought of mapping, but don’t know how exactly

NextJS Cors Block localhost Api

I have two applications, a front end in next and an api made with express, when I try to make a request of type POST, my application front end next blocks the request alleging a problem with cors, it doesn’t even make the request to my backend.

Error:
Access to XMLHttpRequest at ‘http://localhost:3333/deposition/3f0fd7ca-13a1-4f42-8ce3-b6462f5ac9cd’ from origin ‘http://localhost:3000’ 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.

const onSubmit: SubmitHandler<Inputs> = useCallback(
  async data => {
    const response = await api.post(`/deposition/${query.id}`, {
      name: data.name,
      description: data.description,
      stars: data.stars,
      avatar: data.avatar[0],
    });

    console.log(response.data);
  },
  [query.id],
);

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  images: {
    domains: ['localhost'],
  },
};

module.exports = nextConfig;

How can I pass multiple const’s of .entries into one “for” loop

I have this code:

for (const [key, value] of txtfile1.entries()) {
  console.log(`${key}: ${value}`);
}

And I need to pass this loop one more txt file to make something like this:

for (const [key, value] of txtfile1.entries()) && (const [key2, value2] of txtfile2.entries()) {
  console.log(`${key}: ${value} and ${key2}: ${value2}`);
}

So my goal is to use data from two different txt files in the same loop. Pls help!

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

Im keep getting that error while having no idea why. Im trying to connect to my mongodb database but it keeps telling me that “host” is undefined!

Here are my files:

Index.js

const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./config/db");

//Load config
dotenv.config({ path: "./config/config.env" });
console.log("hello");
connectDB();

const app = express();

const PORT = process.env.PORT || 3000;

app.listen(
  PORT,
  console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

The error is in db.js line 11

const mongoose = require("mongoose");

const connectDB = async () => {
  try {
    const conn = mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      //   useFindAndModify: false,
    });
    console.log("hey!");
    console.log(`MongoDB connecteed: ${conn.connection.host}`);
  } catch (err) {
    console.error(err);
    process.exit(1);
  }
};

module.exports = connectDB;

Please let me know if im missing anything.

Thank you!

i have problems using react js

everytime i run nmp install after creating my project…i get this error…i am also using vite with my react app
pls help me

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-android-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”android”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-android-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”android”,”arch”:”arm64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-darwin-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”darwin”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-darwin-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”darwin”,”arch”:”arm64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-freebsd-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”freebsd”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-freebsd-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”freebsd”,”arch”:”arm64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”arm”} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”arm64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-mips64le):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”mips64el”} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-ppc64le):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”ppc64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-riscv64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”riscv64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-linux-s390x):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”linux”,”arch”:”s390x”} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-netbsd-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”netbsd”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-openbsd-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”openbsd”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-sunos-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”sunos”,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-windows-32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”win32″,”arch”:”ia32″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-windows-64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”win32″,”arch”:”x64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/esbuild-windows-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”win32″,”arch”:”arm64″} (current: {“os”:”linux”,”arch”:”ia32″})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {“os”:”darwin”,”arch”:”any”} (current: {“os”:”linux”,”arch”:”ia32″})

audited 306 packages in 7.689s

18 packages are looking for funding
run npm fund for details

found 0 vulnerabilities

How can I execute an http GET request to this code JS

I’m a novice programming, I only have the logic of programming due to my university career but I dedicate myself to the networking section.

I have a POST type API service which I need to convert to GET because a third party system only supports GET type APIs. Try to design the following code in javascript with which I capture the information from the URL and convert it to a POST request and it works perfectly when I call this file from my browser the API is able to complete without problem. However, when I make the GET request to the URL of the file, I can only see its code and the javascript embedded in it is not executed.

Can I solve this somehow?

The API of my service has the following form:

 https://<api-reference-url-method.com>/send
{
 message: 'Hello',
 number: '123456789'
}

And the 3rd party service only accepts one API as follows

 https://<api-reference-url-method.com>/send?message=%message%&number=%number%

The code I designed is the following:

<!DOCTYPE html>
<html>

<body>
<span id="demo1"></span>
<span id="demo2"></span>

</body>

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
    var regex = new RegExp("[\?&]" + name + "=([^&#]*)"),
    results = regex.exec(url);
    return results === null ? "" : decodeURIComponent(results[1].replace(/+/g, " "));
}

var message = getParameterByName('message');
var number = getParameterByName('number');

document.getElementById("demo1").innerText = message
document.getElementById("demo2").innerText = number;


var xmlhttp = new XMLHttpRequest();   
var theUrl = "/json-handler";
var resultado = document.getElementById('demo');
xmlhttp.open("POST", "https://<api-reference-url-method.com>/send", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
        var json = JSON.parse(xmlhttp.responseText);
        console.log(xmlhttp.responseText);
    }
};

xmlhttp.send(JSON.stringify({ "message": message ,"phone": number }));

</script>

</html>

I know that the code is not the best, that’s why I ask for help. I just need this to be functional or a method that will help me modify the original API (POST) to the new API call type (GET)

Possible to have NextJS protect the backend API with JWT?

I am looking for a way to use KeyCloak with JWT and store them in a JS object in memory (not cookie, localStoare, sessionStorage). I use NextJS, and it seams to have two options:

Use static generation to server-render a loading state, followed by
fetching user data client-side.

Fetch user data server-side to eliminate a flash of unauthenticated content.

Not being a native English speaker I am not sure what they exactly mean. What I want is to protect the backend data from unauthorized access.

When I look at https://www.npmjs.com/package/@react-keycloak/ssr it looks like it just limits what React renders to the screen and the backend API is left wide open?

Question

Does anyone know if NextJS supports JWT with KeyCloak to protect the backend API?

How to display the new list from local storage?

How do I display the new list from local storage? When the user inputs a new search, that displays fine, and get’s added to the localstorage. However it doesn’t show the updated list in the last requests on the website. Currently it only shows it when refreshing the website. So basically how do I re-run / re-display the new and updated list from localstorage? Can post the HTML if neccesary

// Local Storage
function SaveDataToLocalStorage(data) {
  var a = [];
  // Parse the serialized data back into an aray of objects
  a = JSON.parse(localStorage.getItem('last-requests')) || [];
  // Push the new data (whether it be an object or anything else) onto the beggining of the array
  a.unshift(data)
  // If more than 5 requests remove (pop) last request
  if (a.length > 5) {
    a.pop()
  }
  // Re-serialize the array back into a string and store it in localStorage
  localStorage.setItem('last-requests', JSON.stringify(a));
displayLastRequests()
};
// Displays last 5 requests/searches
function displayLastRequests() {
  const lastReq = JSON.parse(localStorage.getItem('last-requests'))
  console.log(lastReq)
  // for loop request
  for (req of lastReq) {
    var clone = $($("#last-request-template").html());
    clone.appendTo(".last-requests");
    clone.find(".cityname").text(req.city_name);
    clone.find(".cityweather").text(req.weather);
    clone.find(".imgs").attr('src', req.imgurl);
    clone.find(".citytemp").text(req.city_temp + " °C");
    clone.find(".citywind").text(req.city_wind + " m/s");
  }
};

How to download all modules in the background, right after main page load in Angular 14

Making lazy loading per module is pretty easy in Angular.

const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  }
];

But this forces to me to download the module when I navigate to it the first time.

Is it possible to download ALL modules in the background after the first page load?.

Incompatibility between testcafe and jquery mobile checkboxradio?

Testcafe has unusual behavior when operating a jQuery mobile checkboxradio widget. t.click() results in two click events being fired on the checkbox input. Both of these clicks appear to come from testcafe.

Working vanilla checkbox test:

import { Selector } from 'testcafe';

fixture`checkboxradio test`
    .page`https://html.form.guide/checkbox/html-form-with-checkbox/`;

test('Checkbox state from testcafe', async t => {
        const cb = await Selector('input[type=checkbox]');
        await t.expect(cb.nth(0).checked).eql(false)
                .click(cb.nth(0));

        await t.expect(cb.nth(0).checked).eql(true);
});

jQuery mobile checkbox (fails)

import { Selector } from 'testcafe';

fixture`checkboxradio test`
    .page`https://demos.jquerymobile.com/1.4.5/checkboxradio-checkbox/`;

test('Checkbox state from testcafe', async t => {
        const cb = await Selector('#checkbox-h-2a');
        await t.expect(cb.checked).eql(false)
                .click(cb);

        await t.expect(cb.checked).eql(true);
});

Anyone familiar with this issue? Any workarounds?

How to show selected data in select html?

I have a form.

I use post method this form and backend is PHP.

<div class="form">
            <form action="" method="post" class="mt-2">
                <div class="form-group">
                    <select class="form-control" name="ra" onchange="xx()">
<!--                        <option value="a">a</option>-->
                        <option value="b">b</option>

When I select a or b I can post. It is work but my problem is when I selected b system works according to b but select default show a.

I want to show b or c.

Node.js postman infinite request time(*no errors and database is updated fine) on PUT request

I’ve been stuck on this for way too long without being able to find where is my error, I am making an API with node.js through express and all Restful functions work fine for me except the updating which gets stuck on postman “sending request” while the database is updated without problems, I suspect the error is somewhere in the response but I swear I’ve tried each combination that came to mind to get the response to no avail. Here’s my code for this:

In the router

router.put('/:id', hlpJWT.authenticateToken,  ctrProfile.updateInfo);

In the controller

updateInfo = async function (req,res,next) {
    const input = {
        id: req.params.id,
        name: req.body.name,
        age: req.body.age,
        profile_picture: req.body.profile_picture,
        background_picture: req.body.background_picture,
        email: req.body.email,
        password: await srvAuth.cryptPass(req.body.password),
        city: req.body.city,
        gender: req.body.gender,
    }
        let user = await srvProfile.updateProfile(input);
         if (user)
            res.json(user);
         else {
            res.status(404);
            res.json({error: 'user not found'});
    }
}

in the service

updateProfile = function (input){
    return new Promise((resolve, reject) => {
        query('UPDATE users SET ? WHERE ?', [{ name:input.name, age:input.age,
                profile_picture : input.profile_picture, background_picture:input.background_picture, email:input.email,
                password:input.password, gender:input.gender, city:input.city }, { user_id:input.id }], function(error, result) {
                if(error){
                    return reject(error);
                }
                return resolve(result);
            });
    });
};

Thanks in advance to anyone willing to help