how to make some logic in next js 13 when updating a page and it doesn’t matter at which url the page was updated.
In react it worked when I wrote some logic in App.tsx, it worked wherever the user refreshed the page. please help
Category: javascript
Category Added in a WPeMatico Campaign
Issue with certain properties in metaData in node-oracledb
(I am using node-oracledb thin client v6.2.0)
When I do a simple Select statement like this:
connection.execute( mySqlstring, {}, { outFormat: oracledb.OUT_FORMAT_OBJECT });
The result has metaData like this:
metaData: [
{
name: 'ID',
dbType: [DbType DB_TYPE_NUMBER],
nullable: false,
precision: 10,
scale: 0,
dbTypeName: 'NUMBER',
fetchType: [DbType DB_TYPE_NUMBER],
converter: [Function: converter]
},
But because Electron uses Proxy to send data to the renderer, only valid objects can be send. And dbType, fetchType and converter make this not a valid object.
But I do need the metaData.
This works:
return JSON.parse(JSON.stringify(result,null,2));
But is of course not what I want.
Should I set other options? Or do I have to write code to exclude these fields?
Cant access protected resources even after successful login ( passport oauth2.0 google sign in )
Facing Trouble making protected Resources accessible to Logged in users ( oauth2 google passport.js )
I am able to login and then get redirected to the protected page ( on the frontend).
But when the page renders i send a request to a route in the api called /login/success where i send some user details as response , but before that i check if req.isAuthenticated exists , apparently it exists in the route to which the callback url after google log in , ( callback – ive named it {BACKEND_BASE_URL}/authorize ) redirects ( req.user and req.isAuthenticated ) , but it doesnt seem to exist in any other routes , i am confused right now , i am a noob so i dont exactly know if i should run the passport.authenticate middleware before the logic in all protected Routes or if it should be done only once —
https://github.com/DAObliterator/oauth2_googlesigin... here is the link to the project.
FLOW
/*{CLIENT_URL}/authenticate -> (NOTE - via an anchor tag does not work when i send a get request using axios when click event is fired , throws a NO ACCESS CONTROL ORIGIN on the requested header error at the client side , had to sit a whole day to figure out that anchor tags has to be used to prevent CORS error )*/
//{BACKEND_URL}/login ->
app.get(
"/login",
passport.authenticate("google", { scope: ["email", "profile"] })
);
//Auth Server (google) ->
//{BACKEND_URL}/authorize->
app.get(
"/authorize",
passport.authenticate("google", {
successRedirect: "/protected",
failureRedirect: "/auth/failure",
})
);
//onSuccess
//{BACKEND_URL}/protected->
app.get("/protected", async (req, res) => {
console.log("user-details-2 ", req.user);
if (req.user) {
return res.redirect(${process.env.CLIENT_URL}protectedPage`);`
} else {
return res.redirect(${process.env.CLIENT_URL}authenticate`);`
}
});
//{CLIENT_URL}/protectedPage
import React , { useState , useEffect } from 'react';
import axios from "axios";
export const ProtectedPage = () => {
const [text , setText ] = useState("");
const [access, setAccess] = useState(false);
useEffect(() => {
axios.get("http://localhost:6046/login/success").then((response) => {
console.log(response.data , "response data from /protected n");
setAccess(true);
setText(response.data.user.displayName);
}).catch((error) => {
console.log(error , ' error happened while trying to access protectedResource endpoint')
})
},[])
const handleLogout = () => {
axios.get("http://localhost:6046/logout")
}
return (
<div id="Main" className="w-screen h-screen flex flex-col">
Hello to ProtectedPage <br /> you are{" "}
{access ? text + " and is permitted " : "not-permitted"} to view the protected Resource
{access && (
<button
id="Logout-btn"
className="bg-blue-400 h-16 w-40"
onClick={handleLogout}
>
logout
</button>
)}
</div>
);
}
//{BACKEND_URL}/login/success
app.get("/login/success", (req, res) => {
if (req.isAuthenticated()) {
// If the user is authenticated, respond with user information
res.status(200).json({
error: false,
message: "Successfully Logged In",
user: req.user,
});
} else {
// If the user is not authenticated, respond with an error
res.status(403).json({ error: true, message: "Not Authorized" });
}
});
throws 403 error on the client side
Play Soundcloud sound by hovering over Soundcloud link not the Iframe
Context: Below are the links for Soundcloud music with their corresponding Iframe(HTML Code) and code for Soundcloud widget API(Javascript Code).
Soundcloud Links and Iframes for each one:
1.
<a id="0" href="https://soundcloud.com/leagueoflegends/kda-drum-go-dum">Drum Go Dum</a>
<br />
<iframe class="clickme" id="sc_0" width="300" height="200" allow="autoplay" scrolling="no"
src="https://w.soundcloud.com/player/?url=https://soundcloud.com/leagueoflegends/kda-drum-go-dum&show_artwork=true"
frameborder="0" style="display: 100px">
</iframe>
<a id="1" href="https://soundcloud.com/leagueoflegends/kda-more-feat-madison-beer-gi-dle-lexie-liu-jaira-burns-seraphine">More</a>
<br />
<iframe class="clickme"id="sc_1" width="300" height="200" allow="autoplay" scrolling="no"
src="https://w.soundcloud.com/player/?url=https://soundcloud.com/leagueoflegends/kda-more-feat-madison-beer-gi-dle-lexie-liu-jaira-burns-seraphine&show_artwork=true"
frameborder="0" style="display: 100px">
</iframe>
Soundcloud widget API(Javascript Code):
<script src="https://w.soundcloud.com/player/api.js" type="text/javascript"></script>
<script>
// create widget object to store all the sound widgets, each iframe key will have a separate SC Widget instance
const widget = {}
// Play function to play the current sound, id is the iframe id for hovered widget
function play(target, id) {
// if the widget is not haven't played yet, then create a new widget instance
// and add it to widget object
if (!widget[id]) widget[id] = new SC.Widget(target)
widget[id].bind(SC.Widget.Events.READY, function () {
widget[id].bind(SC.Widget.Events.PLAY, function () {
// get information about currently playing sound
console.log('sound is beginning to play');
});
// get current level of volume
widget[id].getVolume(function (volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget[id].setVolume(50);
// get the value of the current position
widget[id].bind(SC.Widget.Events.FINISH, function () {
// get information about currently playing sound
console.log('replaying sound');
widget[id].seekTo(0);
widget[id].play();
});
});
widget[id].play()
}
// stop the player from which mouseleave has happened
function stop(target, id) {
if (widget[id])
widget[id].pause()
}
$(document).ready(function () {
console.log("ready!");
$(".clickme").mouseenter(function (e) {
console.log('start ');
// Play the current hovered
play(e.currentTarget, e.currentTarget.id)
});
$(".clickme").mouseleave(function (e) {
console.log('finish ');
// Stop currently playing on mouse leave
stop(e.currentTarget, e.currentTarget.id)
});
}());
</script>
Problem: The javascript code above plays the soundcloud sound when you hover over the iframe only. I need help with modifying the code so that when you hover on the link in tags <a></a> it will play the sound instead of hovering over the iframe.
What I did to try to solve the problem: I tried to create a string that represents the various ID’s of multiple iframes but I could not do it successfully and it gave me the error that Soundcloud widget must be an iframe or a string representing the id of the iframe.
Function to get a value depending on conditions, how to call?
So suppose I have this code:
const x = a ? b : c ? d : f;
For readability I can refactor into:
const getX = () => {
if(a) return b;
if(c) return d;
return f;
}
const x = getX();
Now, it seems redudant to make a func just to call it the one time right below it. Is there any other way to write this? Without giving up the benefits of the early returns..
Replace symbol in array of Object keys [duplicate]
I have array of Object as following
I want to replace __ with . in all object keys.
data: [{
"part1_hhrhe__something_1": 999.48,
"abc_do__extra": -766780.56,
"xyz__ppp": 1062.47,
"ddd__5584": -9160.04
},
{
"part1_hhrhe__something_1": 999.48,
"abc_do__extra": -766780.56,
"xyz__ppp": 1062.47,
"ddd__5584": -9160.04
},
{
"part1_hhrhe__something_1": 999.48,
"abc_do__extra": -766780.56,
"xyz__ppp": 1062.47,
"ddd__5584": -9160.04
}]
I am trying to do with following but, not working.
data.map(item => {
item.key.split('__').join('.')
})
expected output:
data: [{
"part1_hhrhe.something_1": 999.48,
"abc_do.extra": -766780.56,
"xyz.ppp": 1062.47,
"ddd.5584": -9160.04
},
{
"part1_hhrhe.something_1": 999.48,
"abc_do.extra": -766780.56,
"xyz.ppp": 1062.47,
"ddd.5584": -9160.04
},
{
"part1_hhrhe.something_1": 999.48,
"abc_do.extra": -766780.56,
"xyz.ppp": 1062.47,
"ddd.5584": -9160.04
}]
Any help would be greatly appreciated.
How to create an infinity multi-item image carousel? (+ Touch and all Plain Vanilla JS and CSS)
It would be awesome to have a image gallery with infinity effect without using external libraries like jQuery or frameworks like Angular. A plain vanilla JS and CSS, so everybody can use.
How to do?
Distinguish reload status of page
I use PerformanceNavigationTiming to check the page’s reload status:
(window.performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming).type === 'reload'
However, if using useNavigate() to navigate the page, navigation will also be understood as the page being reloaded. Is there a way to tell the difference when using useNavigate()?
Unable to get object value from response body in cypress
I am a beginner to Cypress and I am trying to get hands-on in API Testing for Cypress.
I am trying a very basic GET response from the following URL:
https://automationexercise.com/api/productsList
I am trying to get responseCode, but whenever I try to object, I get blank value on it..
my logic is following:
it("Verify All Product response contains correct keys and values", () => {
cy.request("GET","https://automationexercise.com/api/productsList").then((response) => {
expect(response.status).to.eq(200)
expect(response.body).length.to.be.greaterThan(1)
cy.log(response.body.responseCode)
});
});
Let me know, where I am making a mistake.
Thanks.
How to hide the first option in select
I want to hide the “Day” option. It should only appear if nothing is selected.
<select id="day" name="day">
<option disabled selected>Day</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
How it looks at the moment: https://imgur.com/a/tK3bHDX
I tried adding “hidden” to the first option but it didn’t work either. I use Safari as my web browser. Maybe that’s the reason I don’t know.
<option disabled selected hidden>Day</option>
Loading searches (impressions) from google search console and google api
I’m trying to make an analytics page and that also contains having the impressions of the past 30 days. I tried making one using google’s api but the result didn’t work.
My code:
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<script>
function handleClientLoad() {
gapi.load('client', initClient);
}
function initClient() {
gapi.client.init({
apiKey: 'nuh-uh das my api key',
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/webmasters/v3/rest'],
}).then(function () {
// API is ready
// You can make requests to the Search Console API here
fetchData(); // Call the function to fetch and display data
});
}
function fetchData() {
gapi.client.webmasters.searchanalytics.query({
siteUrl: 'https://masterrealm.net',
startDate: '2023-01-01',
endDate: '2023-01-31',
dimensions: ['query'],
}).then(function (response) {
// Process the response and display search data on your webpage
const searchesElement = document.getElementById('searches');
if (searchesElement) {
searchesElement.textContent = response.result.rows[0].keys[0];
}
});
}
</script>
any help incase I have done something wrong?
Adding new row through javascript in UI [closed]
I am trying to read a DB Table and then displaying the contents on UI.
Able to read table and display on UI.
I want to add functionality of adding new row in the beginning through an icon(+)- have put icon already, but not working out when clicking on + icon, please help- I am new to UI tech stack.
below is the code snippet-
DB read and display on UI result-
enter image description here
When trying to add new row, its showing like below-
enter image description here
can you help me with this api and function call? [closed]
app.post('/formController', async (req, res) => {
const { proId } = req.body;
const orderId = proId;
let mainId = '';
const response = await axios.get(`https://abc-in.shopify.com/api/21/name=${orderId}`, {
auth: {
username: apiKey,
password: passToken
}
});
const orderData = result.orders;
const swid = orderData[0].fulfillments[0].tracking_number;
const newToken = await getNewToken();
const getCtime = await axios.get(`https://app.postLine.in/l1/v7/track/${swid}`, {
auth: {
Bearer: `${newToken}`
}
});
const ans = getCtime.data;
const mainTime = ans.track.ctime;
const getStatus = ans.track.status;
returnValidityChecker(mainTime);
mainId = orderData[0].id;
orderStatus = orderData[0].fulfillment_status;
const message = "Order was returned";
let valuesArray = [mainId, message];
res.json({ validator, getStatus });
if (response.status === 200) {
await noteController(orderId);
}
});
async function noteController(orderId) {
const getTagsOptions = {
method: 'GET',
url: `https://abc-in.shopify.com/api/21/name=${orderId}.json`,
};
console.log("this is the order id before try " + orderId);
try {
console.log("this is before getTagsOptions ");
const response = await axios(getTagsOptions);
console.log('Response Status Code:', response.status);
const existingTags = response.data.order.tags;
console.log("this is the existing tags " + existingTags);
const updatedTags = `${existingTags},Return Initiated`;
const updateTagsOptions = {
method: 'PUT',
url: `https://abc-in.shopify.com/api/21/name=${orderId}.json`,
headers: {
'Content-type': 'application/json',
},
data: {
order: {
id: orderId,
tags: updatedTags,
},
},
};
const updateResponse = await axios(updateTagsOptions);
} catch (error) {
}
}
I have a function called noteController(), it fetches the data of tags of a products and than put new tags, now I have called this function inside an api called /formContorller, it reaches to function and enters into the function but just after the try catch block , exactly at line const response = await axios(getTagsOptions) it gives error Error: Request failed with status code 404, and does not works further, when I run noteController() function independently in different file, it runs perfectly but when i copy paste the same code in this file(pasted above) and call it inside api, it gives error and does not work in try catch block , can anyone help me with this.
Style and script in iframe leak to parent page in Nuxt 3
In my index.vue page I create an iframe element, which is rendering my iframe.vue page:
// index.vue
<template>
<div>This is index page content!</div>
<iframe src="/iframe"></iframe>
</template>
// iframe.vue
<script setup>
console.log('Hello World inside iframe!');
</script>
<template>This is iframe content.</template>
<style>
* {
color: red;
}
</style>
The problem is that both style and script leak from iframe to parent page (index.vue).
All elements are red and I also see message in console log.
How to prevent iframe from applying styles and script to parent page?
How to make multiple input in vue 3?
So I’m working on a project in company, currently we’re moving from Vue 2 to Vue 3, but not using composition API
So there’s a component array-field, which extends vuetify’s v-text-field, allowing us to create multiple inputs, and results from these inputs is sent to the backend as an array
This component looks like this:
<template>
<div
ref="array_field"
class="array_field__wrapper"
>
<v-text-field
v-for="(element, index) in elements"
v-bind="$attrs"
:key="index"
v-model="elements[index]"
:label="isFirstValue(index) ? labelText : ''"
class="array_field"
:rules="rules.name"
dense
outlined
:class="{ 'indent_right': !isLastValue(index) }"
:append-inner-icon="isEmptyArray ? null : $icons['mdi-close']"
:append-icon="isLastValue(index) ? $icons['mdi-plus'] : null"
@click:append="addValue(index)"
@click:append-inner="deleteValue(index)"
@update:modelValue="onInput"
@blur="onBlur"
>
<template #message="{ message }">
{{ translateError(errorMessage, message) }}
</template>
</v-text-field>
</div>
</template>
<script>
import { isEmptyOrNil } from '@/utils'
export default {
props: {
value: Array,
labelText: String,
translateError: Function,
errorMessage: String
},
data () {
return {
elements: !isEmptyOrNil(this.value) ? this.value : [''],
isEmptyArray: isEmptyOrNil(this.value),
rules: {}
}
},
watch: {
elements (value) {
this.$emit('input', this.isEmptyArray ? [] : value)
}
},
mounted () {
if (!isEmptyOrNil(this.value) && isEmptyOrNil(this.value[0])) {
this.setLabelPositionOnTop()
}
},
methods: {
isFirstValue (index) {
return index === 0
},
isLastValue (index) {
return index === this.elements.length - 1
},
addValue (index) {
this.elements[index + 1] = ''
this.isEmptyArray = false
this.setLabelPositionOnTop()
},
deleteValue (index) {
if (this.elements.length > 1) {
this.elements.splice(index, 1)
} else {
this.elements = ['']
this.isEmptyArray = true
this.setLabelPositionByDefault()
}
},
setLabelPositionOnTop () {
const commonWrapper = this.$refs.array_field.firstChild.firstChild.firstChild
const legendWrapper = commonWrapper.firstChild
const labelWrapper = legendWrapper.nextSibling
const label = labelWrapper.firstChild
label.classList.add('v-label--active')
const legend = legendWrapper.querySelector('legend').querySelector('span')
legend.style.color = 'white'
legend.style.fontSize = '12px'
legend.style.textWrap = 'nowrap'
legend.style.padding = '2px'
const labelText = label.innerHTML
legend.innerHTML = labelText
},
setLabelPositionByDefault () {
const commonWrapper = this.$refs.array_field.firstChild.firstChild.firstChild
const legendWrapper = commonWrapper.firstChild
const labelWrapper = legendWrapper.nextSibling
const label = labelWrapper.firstChild
label.classList.remove('v-label--active')
const legend = legendWrapper.querySelector('legend').querySelector('span')
legend.innerHTML = 'u200b'
legend.style.padding = 0
},
onInput (value) {
this.isEmptyArray = false
console.log(value)
},
onBlur () {
if (!this.isEmptyArray) {
this.setLabelPositionOnTop()
}
}
}
}
</script>
Basically we have a dialog where we have multiple array-fields, we change them and send them to the backend, and we use array-field like this:
<isf-array-field
v-model="authSource.add.ldap_phone"
/>
Data in dialog looks like this:
data () {
const authSourceTemplate = {
add: {
name: null,
url: null,
base_dn: null,
login: null,
password: null,
type: 'ldap',
ldap_filter: null,
ldap_phone: [],
ldap_email: [],
ldap_uuid: [],
ldap_lastname: [],
ldap_firstname: [],
ldap_middlename: [],
ldap_internal_phone: [],
with_internal_phone: null
}
}
return {
authSourceTemplate: authSourceTemplate,
authSource: this.clone(authSourceTemplate),
actionPending: false,
authSourcesDialogsProp: this.authsourcesDialogs,
rules: {}
}
So basically we use the fields from data() in v-model for an array-field, I don’t know the logic behind it, but basically our array-field should return an array of strings
But my problem currently is that when I input something in text-field, v-model type changes from an array to string, and because of it i can’t send the request to the backend
In previous version, where we used Vue 2, everything is okay, but with Vue 3 I have such problem and I can’t figure out why