There are two buttons at the top of one box, and the two buttons each have different contents, so I’m going to do coding that shows different results with a Each other, what should I do?
Category: javascript
Category Added in a WPeMatico Campaign
Cannot send error message with express 4.x
Maybe I am missing something obvious here but when I send my status and message response after my post request, I cannot see any error message in my response
return res.status(401).send(info.errors);
// I can log out info.errors and it says "Unable to use this email address"
Code is as follows
// auth.js
export default (app, passport) => {
app.post('/auth/api/sign_up', (req, res, next) => {
signup(req, res, next, passport);
});
};
// signup.js
export default async (req, res, next, passport) => {
passport.authenticate('local-signup', (err, user, info) => {
if (info.errors || err) {
console.log(info.errors);
// info.errors prints out "Unable to use this email address"
return res.status(401).send(info.errors);
} else {
res.status(200).send(info.success);
}
})(req, res, next);
};
I believe I am using the correct middleware as declared in my server.js file
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
Could anyone point out where I am going wrong please? (if i’ve missed any setup code in the question please ask and ill add it)
how to wait for one field yup to trigger another reacts
how to wait seconds to validate field with yup? I need city code to wait a few seconds because of the state field
const schema = yup.object().shape({
state: yup.number().nullable().required('required'),
city: yup.number().nullable().required('required')
})
FindOne does not correctly compare string Express and MongoDB
I am doing a Role validation with the database using Express, express-validator and MongoDB to create a new user checking that the User Role exists in the Database.
In my route using express-validator I verify that the Role exists using findOne to be able to post a new user but even if the role is correct it always tells me that the role does not exist.
Route:
import Role from '../models/role';
import { check } from 'express-validator';
router.post('/',
[
check('role').custom( async (role = '') => {
let roleExists = await Role.findOne( { role } );
if ( !roleExists ) {
throw new Error('El Rol no es vĂ¡lido');
}
} ,
),
], newUser);
Role Model
import { Schema, model } from "mongoose";
const RoleSchema = Schema (
{
role: {
type: String,
required: [true, 'El Rol es obligatorio']
}
}
);
module.exports = model('Role', RoleSchema);
Attached Document in MongoDB, request with postman and postman response.
Array.prototype.find() in PHP that returns reference
I’m trying to make a function that works like Array.prototype.find() in javascript but for PHP.
My array have that structure :
$array=[
["id"=>54,"type"=>5,"content"=>[
["id"=>99, "type"=>516],
["id"=>88, "type"=>464],
["id"=>41, "type"=>845]
],
["id"=>54,"type"=>55,"content"=>[
["id"=>54, "type"=>578],
["id"=>54, "type"=>354],
["id"=>75, "type"=>458]
],
["id"=>65,"type"=>59,"content"=>[
["id"=>87, "type"=>5454],
["id"=>65, "type"=>245],
["id"=>65, "type"=>24525]
]
]
Then I created my function to search like in javascript :
function array_find($array,$function){
foreach($array as $value){
if($function($value)){
return $value;
}
}
}
$mycontent=array_find($array,function($foo){ return $foo["id"]==$id && $foo["type"]==$type; })["content"]
It’s working. However i want the returned result to be a reference and not a value, so i can later add/remove elements inside of it.
How can i do this?
Adding Javascript Widget to a Single Tumblr Post
I only do scientific programming so I am not too familiar with javascript. I am trying to add a widget to one single tumblr post. The website I got the widget from makes it specifically for tumblr and it is:
<div class="shopthepost-widget" data-widget-id="4665345"><script type="text/javascript">!function(w,i,d,g,e,t){d.getElementById(i)||(element=d.createElement(t),element.id=i,element.src="https://widgets.rewardstyle.com"+e,d.body.appendChild(element)),w.hasOwnProperty(g)===!0&&"complete"===d.readyState&&w[g].init()}(window,"shopthepost-script",document,"__stp","/js/shopthepost.js","script")</script><div class="rs-adblock"><img src="https://assets.rewardstyle.com/production/424ab6aff12fe31b5b93d8f5ce7cc70d2953e565/images/search/350.gif" onerror='this.parentNode.innerHTML="Disable your ad blocking software to view this content."' style="width: 15px; height: 15px"><noscript>JavaScript is currently disabled in this browser. Reactivate it to view this content.</noscript></div></div>
If this is added to the actual theme on tumblr, it works great. However, I am trying to put this in just one post on tumblr. When I’m trying to make the post I will go to the html and add it in there but it will not actually show up on the site. Any tips on how to solve this? Thank you in advance.
How to make android apps without[android-sdk] (I can help you)
I have a x86 computer and can’t install android-sdk. Why am I getting an error on install (if you are getting this error then I can help you) using the androidjs
(HOW TO INSTALL [androidjs])
Find on web https://androidjs.github.io
Enter in getting started if you having problems in installation enter on here :
https://medium.com/@Chhekur/how-to-build-android-apps-with-node-js-using-android-js-2aa4643be87b
(requiries node.js)
Comment if i help you!
Dynamically add input type select with options generate by api
hello I try to generate a decision tree when the user chooses a reason option that generates the reasons and we create a select, if he clicks on an option and the API does not return an empty array another select below with sub-reasons which is created all this is dynamically created according to the response of the API as long as it does not return an empty array and so on
<template>
// the first select option don't generate
<select v-model="reasonOne" @change="eventOne(reasonOne)">
<option
v-for="(reason, key) in reasonsOne"
:key="key"
:value="reason.value"
:selected="reason.item === reasonOne"
@click="eventOne(reason.item)"
>
{{ reason.item }}
</option>
</select>
// the div with generate dynamically all select option
<div v-if="showSav">
<div id="select-pattern" class="step-two__select-wrapper" />
</div>
<template/>
<script>
async eventOne(option) {
let reasonsReturn = await customerApi.getReturnPattern(
app,
this.detailReturn.sku.product.id
);
if (!this.reasonsReturn.length) {
this.showSav = false;
}
let selectPattern = document.createElement('select');
let target = document.getElementById('select-pattern');
selectPattern.className = 'select-create';
selectPattern.id = 'create-input';
target.appendChild(selectPattern);
for (let item of reasonsReturn) {
let optionPattern = document.createElement('option');
optionPattern.value = item.id;
optionPattern.text = item.name;
selectPattern.appendChild(optionPattern);
}
document
.getElementById('create-input')
.addEventListener('change', async function () {
let reasonData = await customerApi.getReturnPattern(
app,
this.value
);
});
}
</script>
I was able to create the first select with it but the rest I am stuck I think we have to make a loop on select which will be created if the API returns data. i don’t know how to do it while calling the api every time when the option changes
Using a Promise to check if a new random number has been generated
I’m using Chainlink Oracles to get random numbers. This process of getting a random number takes a while, and I simply run a function that prints out the current number to me by console. This way I know if a new one has been generated.
What I want is to automate this process: when a new number is generated, I would like to display a message to the user (in my fronted).
Hey, a new number has been generated.
From a logical point of view, how can I know when a new random number has been generated (that is, when has my variable changed its value)?
Finally, how could I use Promise to do it?
If you are curious, this is my functions. But I rather to understand the concept.
async function async_randomResult(data) {
if (typeof window.ethereum !== 'undefined') {
await requestAccount();
const provider = new ethers.providers.Web3Provider(window.ethereum)
const contract = new ethers.Contract(generatorAddress, Generator.abi, provider);
try {
const signer = provider.getSigner();
// result stores the random number
const result = await contract.connect(signer).randomResult();
} catch (err) {
console.log("Error: ", err)
}
}
}
How can i make my function that change the className when i click, works?
i hope you guys fine, well..
I’m doing a To Do List, and there is a problem in my code, which I’ve been trying to solve for a few days, and no effective results was made..
i simplified my code, just to show the real problem:
Link to jsfiddle : https://jsfiddle.net/myqrzcs2/
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
const completedLine = document.querySelector('ol');
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
i.addEventListener('click', function semNomeDois() {
listas.forEach((j) => j.classList.remove('selected'));
this.classList.add('selected');
});
});
}
}
completedLine.addEventListener('click', umClick);
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.lista:focus {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
Here i can show you, what happen, i click for the first time, and then the .lista:focus works, and show that i click in the element, ut the class wasnt add..
but when i click again, works perfectly…
Cannot rename file with ngx-awesome-uploader
I’m using https://www.npmjs.com/package/@sleiss/ngx-awesome-uploader and I cannot find a way to rename the file before uploading.
I’ve checked the methods, and there seems to be none.
I can rename the file in the adapter, and it uploads with the new name, but on the file list it’s still with the old name. So when I try to delete it, it looks for the file with the old name.
Is there a way to rename the file and make it available to the list of files?
Thank you!
I don’t understand why my code have this errors
When I start my react App I have this error “Use ‘stats.errorDetails: true’ resp. ‘–stats-error-details’ to show it.” and I don’t understand why, there a no response on the web so please help me…
React navigation bar is in the screen even though it is not on the router
We are trying to implement a react project that has 3 different types of the same application for 3 different purposes. Think of it like the user will choose which to use on the main screen. All 3 types has similar but different page structure, different navbar etc.
I used a router for the main page where they choose which application type they want to go, with path “/”, and used different routers for different types for applications because their navbar etc. is different. But the navbar appears in the main screen even while it is not present in the router.
I know it sounds complicated but I will show it with code snippets and screenshots.
App.js
function App() {
return (
<>
<Router>
<Routes>
<Route path = "/" exact element={<CirclePage />}/>
</Routes>
</Router>
<Router>
<Routes>
<Route path = "/homepage-clubs" exact element={<HomepageClubs />}/>
</Routes>
</Router>
<Router>
<Navbar/>
<Routes>
<Route path='/homepage' exact element={<Homepage />}/>
<Route path='/events' exact element={<Events/>}/>
<Route path='/clubs' exact element={<Clubs/>}/>
<Route path='/contact' exact element={<Contact/>}/>
<Route path='/notifications' exact element={<Notifications/>}/>
<Route path='/profile' exact element={<Profile/>}/>
</Routes>
</Router>
</>
);
}
export default App;
Navbar is the navbar I wrote in react.
The home screen is like this atm: application screen at first initialization
I have no clue why there is a navbar below the screen. I may not have understood how really routers work, I am not sure. I need that navbar to go away because every type of application will have a different kind of navbar (I will create different navbars for them) and navbar should not be visible on the main screen. What could be the problem?
Clash Royale Node Fetch with Key
Im trying to make a discord bot where if you type -cr into the chat, it takes the Arguments of the user (Being the Clash Royale Player’s player tag) and would then use the package node-fetch to receive data with my specified endpoint. I am constantly running into the error of { reason: 'accessDenied', message: 'Invalid authorization' }. Im rather new to this stuff, especially API’s, but im hoping to access certain data which I can decide later on (Which I know how to do). My code is :
const fetch = require('node-fetch')
module.exports = {
name: 'clash',
aliases: ['cr', 'clashroyale'],
category: 'This',
utilisation: '{prefix}clash',
async execute(client, message) {
var msgArgs = message.content.slice(this.name.length + 1)
var endpoint = `/players/${msgArgs}`
var url = `https://api.clashroyale.com/v1`
var token = `hidingmytoken`
fetch(url + endpoint, {
method: 'POST',
headers: {
"Authorization": token
}
}).then(data => data.json()).then(json => {
console.log(json)
})
},
};
The message parts with msgArgs and discord sides all work but fetching that clash Royale API is a big hurdle for me. The API for Clash Royale can be found here https://developer.clashroyale.com/#/documentation and Im just generally stuck on this whole concept. Im using version 2.6.6 of node-fetch so I can use the require() method which should work if that does matter. In general, how can I pass my token properly to receive that API data?
How can I update parent Class proprety from a child Class?
Main class:
class MainClass {
constructor(value) {
this.config = {
myValue: value
};
this.opperations = new Operations(this.config);
}
}
Operations:
class Operations {
constructor(config) {
this.config = config;
}
specialMethod() {
let newValue = this.config.myValue + 1;
// what do I need to do in order to update the config in the MainClass?
}
}
This is how I ideally want to use this:
let sample = new MainClass(1);
console.log(sample.config.myValue) // Output: 1
sample.opperations.specialMethod();
console.log(sample.config.myValue) // Output: 2
Since the config is passed by reference, I do not seem to be able to modify the value. It’s probably a noob question, but can someone give me an idea?

