Category: javascript
Category Added in a WPeMatico Campaign
Why is my Webrtc video call not working on mobile devices?
I have tested my video call component in my Vite react app and it’s working in firefox/chrome/safari (on OSX) and chrome/firefox (on my ubuntu machine). However, on IOS it only connects audio.
I’ve wasted far too much time on this and would really appreciate some help.
Since there are a lot of experts here I think it is likely that someone will have a very helpful educated guess without having to debug anything.
I need to have this working on chrome/safari on IOS and chrome on Android.
Here is the component:
import React, { useEffect, useRef, useState } from "react";
import io from "socket.io-client";
import { useSelector, useDispatch } from "react-redux";
import { allowedToCall } from "../features/call/CallSlice";
import { useNavigate } from "react-router-dom";
import fullScreenIcon from "../img/fullscreen_icon.png";
import screenShareIcon from "../img/screenshare_icon.png";
import "webrtc-adapter";
import "./Call.css";
import Page from "../components/Page";
const Call = () => {
const [loading, setLoading] = useState(true);
const { successMessage, errorMessage } = useSelector(
(state) => state.call
);
const prevSuccessMessage = useRef();
const prevErrorMessage = useRef();
const dispatch = useDispatch();
const navigate = useNavigate();
const userVideo = useRef();
const partnerVideo = useRef();
const peerRef = useRef();
const socketRef = useRef();
const otherUser = useRef();
const userStream = useRef();
const [waiting, setWaiting] = useState(false);
const container = useRef();
const [isFullscreen, setIsFullscreen] = useState(false);
const [isScreenSharing, setIsScreenSharing] =
useState(false);
useEffect(() => {
dispatch(allowedToCall());
return () => {
if (userStream.current) {
userStream.current.getTracks().forEach((track) => {
track.stop();
});
}
};
}, []);
useEffect(() => {
const configuration = async () => {
userStream.current =
await navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
});
socketRef.current = io();
socketRef.current.emit("join");
socketRef.current.on("otherUser", (userID) => {
setLoading(false);
setWaiting(false);
callUser(userID);
otherUser.current = userID;
});
socketRef.current.on("waiting", () => {
setWaiting(true);
setLoading(false);
});
socketRef.current.on("userJoined", (userID) => {
setWaiting(false);
setLoading(false);
otherUser.current = userID;
});
socketRef.current.on("offer", handleRecieveCall);
socketRef.current.on("answer", handleAnswer);
socketRef.current.on(
"ice-candidate",
handleNewICECandidateMsg
);
};
if (
successMessage &&
prevSuccessMessage.current !== successMessage
) {
prevSuccessMessage.current = successMessage;
console.log("successMessage", successMessage);
configuration();
return;
}
if (
errorMessage &&
prevErrorMessage.current !== errorMessage
) {
prevErrorMessage.current = errorMessage;
console.log("errorMessage", errorMessage);
setTimeout(() => {
navigate("/appointments");
}, 3000);
return;
}
}, [successMessage, errorMessage, dispatch, navigate]);
useEffect(() => {
if (userStream.current && !waiting && !loading) {
userVideo.current.srcObject = userStream.current;
}
}, [waiting, loading]);
const callUser = (userID) => {
peerRef.current = createPeer(userID);
userStream.current
.getTracks()
.forEach((track) =>
peerRef.current.addTrack(track, userStream.current)
);
};
function createPeer(userID) {
const peer = new RTCPeerConnection({
iceServers: [
{
urls: "stun:stun.stunprotocol.org",
},
{
urls: "turn:numb.viagenie.ca",
credential: "muazkh",
username: "[email protected]",
},
],
});
peer.onicecandidate = handleICECandidateEvent;
peer.ontrack = handleTrackEvent;
peer.onnegotiationneeded = () =>
handleNegotiationNeededEvent(userID);
return peer;
}
function handleNegotiationNeededEvent(userID) {
peerRef.current
.createOffer()
.then((offer) => {
return peerRef.current.setLocalDescription(offer);
})
.then(() => {
const payload = {
target: userID,
caller: socketRef.current.id,
sdp: peerRef.current.localDescription,
};
socketRef.current.emit("offer", payload);
})
.catch((e) => console.log(e));
}
function handleRecieveCall(incoming) {
peerRef.current = createPeer();
const desc = new RTCSessionDescription(incoming.sdp);
peerRef.current
.setRemoteDescription(desc)
.then(() => {
userStream.current
.getTracks()
.forEach((track) =>
peerRef.current.addTrack(
track,
userStream.current
)
);
})
.then(() => {
return peerRef.current.createAnswer();
})
.then((answer) => {
return peerRef.current.setLocalDescription(answer);
})
.then(() => {
const payload = {
target: incoming.caller,
caller: socketRef.current.id,
sdp: peerRef.current.localDescription,
};
socketRef.current.emit("answer", payload);
});
}
function handleAnswer(message) {
const desc = new RTCSessionDescription(message.sdp);
peerRef.current
.setRemoteDescription(desc)
.catch((e) => console.log(e));
}
function handleICECandidateEvent(e) {
if (e.candidate) {
const payload = {
target: otherUser.current,
candidate: e.candidate,
};
socketRef.current.emit("ice-candidate", payload);
}
}
function handleNewICECandidateMsg(incoming) {
const candidate = new RTCIceCandidate(incoming);
peerRef.current
.addIceCandidate(candidate)
.catch((e) => console.log(e));
}
function handleTrackEvent(e) {
partnerVideo.current.srcObject = e.streams[0];
}
const handleFullscreen = () => {
if (container.current) {
if (!isFullscreen) {
if (container.current.requestFullscreen) {
container.current.requestFullscreen();
} else if (container.current.mozRequestFullScreen) {
container.current.mozRequestFullScreen();
} else if (
container.current.webkitRequestFullscreen
) {
container.current.webkitRequestFullscreen();
} else if (container.current.msRequestFullscreen) {
container.current.msRequestFullscreen();
}
setIsFullscreen(true);
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
setIsFullscreen(false);
}
}
};
const toggleScreenShare = async () => {
if (!isScreenSharing) {
const screenStream =
await navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true,
});
userStream.current = screenStream;
userVideo.current.srcObject = screenStream;
} else {
const camStream =
await navigator.mediaDevices.getUserMedia({
audio: true,
video: true,
});
userStream.current = camStream;
userVideo.current.srcObject = camStream;
}
setIsScreenSharing(!isScreenSharing);
if (otherUser.current) {
callUser(otherUser.current);
}
};
return (
<Page showMenu={true}>
<h2>Video Calls</h2>
{loading && <h3>Loading...</h3>}
{waiting && <h3>Waiting for other user...</h3>}
{waiting === false && loading === false && (
<div className="video__container" ref={container}>
<video
className="video__user-video"
ref={userVideo}
autoPlay
/>
<video
className="video__partner-video"
ref={partnerVideo}
autoPlay
/>
<img
className="video__full-screen-icon"
src={fullScreenIcon}
alt="fullscreen"
onClick={handleFullscreen}
/>
<img
className="video__screen-share-icon"
src={screenShareIcon}
alt="screenshare"
onClick={toggleScreenShare}
/>
</div>
)}
</Page>
);
};
export default Call;
I tried adding the adapter.js polyfill (webrtc-adapter package) for non-compliant browsers, but it didn’t seem to make a difference.
My Bot is having trouble changing nicknames on my server
My Discord Bot, made in nodeJS, sometimes changing the nickname, sometimes not. All other functions are working properly, however when someone sends the Modal. There is a chance that their nickname will be changed according to the button they selected, which is described in the code, but there is an even greater chance that the person’s nickname will not be changed. I wanted to know if it’s an error in the code, or in my server. Bot role is set to admin
Some parts of the code are in Portuguese(BR)
Code:
client.on('interactionCreate', async (interaction) =>
{
try {
if(interaction.isButton()) //Every Button Pressed
if(interaction.customId == process.env.FIRST_ROLE)
{
const role = interaction.guild.roles.cache.get(process.env.FIRST_ROLE)
if(!role) //a
{
return;
}
//If the member has the role.
//const interactionMember = interaction.guild.members.cache.get(interaction.user.id); //Member that interact
//Modal Part
const modal = new ModalBuilder(
{
customId: `rolePMSetModal-${interaction.user.id}`,
title: 'Informações',
});
const nameInput = new TextInputBuilder(
{
customId: 'nameInput',
label: process.env.FIRST_INPUT_TEXT,
style: TextInputStyle.Short,
});
const idInput = new TextInputBuilder(
{
customId: 'idInput',
label: process.env.SECOND_INPUT_TEXT,
style: TextInputStyle.Short,
});
const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(idInput);
const nameThatUserSelected = null;
const idThatUserSelected = null;
modal.addComponents(firstActionRow, secondActionRow);
await interaction.showModal(modal)
}
if(interaction.customId == process.env.SECOND_ROLE) //Butoes De Selecionar Set
{
const role = interaction.guild.roles.cache.get(process.env.SECOND_ROLE)
if(!role) //s
{
return;
}
//If the member has the role.
//const interactionMember = interaction.guild.members.cache.get(interaction.user.id); //Member that interact
//Modal
const modal = new ModalBuilder(
{
customId: `roleExercitoSetModal-${interaction.user.id}`,
title: 'Informações',
});
const nameInput = new TextInputBuilder(
{
customId: 'nameInput',
label: process.env.FIRST_INPUT_TEXT,
style: TextInputStyle.Short,
});
const idInput = new TextInputBuilder(
{
customId: 'idInput',
label: process.env.SECOND_INPUT_TEXT,
style: TextInputStyle.Short,
});
const firstActionRow = new ActionRowBuilder().addComponents(nameInput);
const secondActionRow = new ActionRowBuilder().addComponents(idInput);
modal.addComponents(firstActionRow, secondActionRow);
await interaction.showModal(modal)
}
if(interaction.isModalSubmit)
{
if(interaction.customId == `roleExercitoSetModal-${interaction.user.id}`)
{
const role = interaction.guild.roles.cache.get(process.env.SECOND_ROLE)
const nameValue = interaction.fields.getTextInputValue('nameInput')
const idValue = interaction.fields.getTextInputValue('idInput')
if(Number.isInteger(idValue)) return;
if(nameValue.length > 12) return;
try {
interaction.guild.members.cache.get(interaction.user.id).setNickname(`[AL SD | EB] ${nameValue} | ${idValue}`).catch(error => {console.log('There is a error to change nickname!')});
interaction.member.roles.add(process.env.SECOND_ROLE);
interaction.member.roles.add(process.env.MAIN_ROLE);
interaction.guild.channels.cache.get(process.env.LOG_CHANNEL).send(`Usuario: ${interaction.user}, Selecionou Uma Guarnição...nGuarnição: ${role}nId: **${idValue}**nNome: **${nameValue}**`); //Log
const replyMsg = interaction.reply("```Usuario Setado!```");
if(replyMsg){
interaction.deleteReply(replyMsg);
} else {
console.log('Nao foi possivel Deletar A Mensagem.')
}
} catch (error) {
console.log(error);
}
}
if(interaction.customId == `rolePMSetModal-${interaction.user.id}`)
{
const role = interaction.guild.roles.cache.get(process.env.FIRST_ROLE)
const nameValue = interaction.fields.getTextInputValue('nameInput')
const idValue = interaction.fields.getTextInputValue('idInput')
if(Number.isInteger(idValue)) return;
if(nameValue.length > 12) return;
try {
interaction.guild.members.cache.get(interaction.user.id).displayName.se(`[ALN | PMA] ${nameValue} | ${idValue}`).catch(error => {console.log('There is a error to change nickname!')});
interaction.member.roles.add(process.env.FIRST_ROLE);
interaction.member.roles.add(process.env.MAIN_ROLE);
interaction.guild.channels.cache.get(process.env.LOG_CHANNEL).send(`Usuario: ${interaction.user}, Selecionou Uma Guarnição...nGuarnição: ${role}nId: **${idValue}**nNome: **${nameValue}**`); //Log
const replyMsg = interaction.reply("```Usuario Setado!```");
if(replyMsg){
interaction.deleteReply(replyMsg);
} else {
console.log('Nao foi possivel Deletar A Mensagem.')
}
} catch (error) {
console.log(error);
}
}
}
} catch (error) {
console.log(error);
}
})
I am looking to know what is the problem with the Bot
How can I write a function that parses nested strings with brackets and turns them into an array
I’m trying to write a function that parses strings like the following
GEYDQORRGM5D[C[M[A,I,Q,Y],NA],O,Q,S] and turns it into an array like the following
[ 'GEYDQORRGM5DCMA', 'GEYDQORRGM5DCMI', 'GEYDQORRGM5DCMQ', 'GEYDQORRGM5DCMY', 'GEYDQORRGM5DCNA', 'GEYDQORRGM5DO', 'GEYDQORRGM5DQ', 'GEYDQORRGM5DS' ]
I’ve tried the following code and it works for some of the strings but most of them don’t work!!
let regex = /([A-Z0-9]+)(?:[([A-Z,]+)])?/g
const result = []
let match;
while ((match = regex.exec(input)) !== null) {
const prefix = match[1];
const suffixes = match[2] ? match[2].split(",") : [""];
for (const suffix of suffixes) {
result.push(prefix + suffix);
}
}
const newResult = []
for (let i = 1; i < result.length; i++) {
newResult.push(result[0] + result[i])
}
return newResult
}
const input = 'GEYDQORRGM5D[C[M[A,I,Q,Y],NA],O,Q,S]';
const output = splitAndAddString(input);
console.log(output);
it returns [ 'GEYDQORRGM5DC', 'GEYDQORRGM5DMA', 'GEYDQORRGM5DMI', 'GEYDQORRGM5DMQ', 'GEYDQORRGM5DMY', 'GEYDQORRGM5DNA', 'GEYDQORRGM5DO', 'GEYDQORRGM5DQ', 'GEYDQORRGM5DS' ] when its supposed to return [ 'GEYDQORRGM5DCMA', 'GEYDQORRGM5DCMI', 'GEYDQORRGM5DCMQ', 'GEYDQORRGM5DCMY', 'GEYDQORRGM5DCNA', 'GEYDQORRGM5DO', 'GEYDQORRGM5DQ', 'GEYDQORRGM5DS' ]
I want to create a spinner after submitting the form. I have a flask endpoint to do calculation and will redirect to new page
I want to create a spinner after submitting the form. I have a flask endpoint to do calculation and will redirect to new page after doing the calculations.
I have created html form for submit. A spinner should come after submitting the form
nodejs crypto.createhash(‘sha256’) produces different hash for the same response object
I am getting a response from a server every minute and creating a hash with it.
After each fetch from server the hash created is different although they are identical when checked in jsondiff.
let etagh = createHash('sha256').update(JSON.stringify(response.json.data)).digest('hex').toString()
reply.header('etag',etagh)
The response.json.data is always the same but the etagh changes after every fetch call. After every fetch call, the response.json value is updated.
Turning a value in an JSON array into contents of a downloadable pdf by jsPDF
I am quite new to js and want to turn a value inside an json array into contents of a downloadable pdf
like:
<div class="container">
<input type="button" value="Create PDF"
onclick="generatePDF()">
</div>
<script type="text/javascript">
const data = {
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true
}
const pdfvalue = tree[1];
function generatePDF() {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text(pdfvalue, 100, 100);
doc.save("newFile.pdf");
}
</script>
I just want to put “Metro City” only into the PDF, but it says invalid arguments passed to jsPDF, is there any way that i could do it?
ClearInterval() although with ID is not working
I have a code when a timer is shown and removed using 2 functions repeatedly by using SetInterval. However when the timer is finished I am trying to clear the SetInterval With ClearInterval but this is not working. When setInterval and ClearInterval set outside gettimer function the they work properly as well. Can someone help?
>declaring const M1 and M2
let M1, M2
>functions
function ShowScrollBar(){
ScrollContainer.classList.add('show-scroll-container')
}
**function TimeShowscrollBar(){
M1 = setInterval(ShowScrollBar,3000)
}**
function RemoveScrollBar(){
ScrollContainer.classList.remove('show-scroll-container')
}
**function TimeRemovecrollBar(){
M2 = setInterval(RemoveScrollBar,6000)
}**
**function ClearTimeShowscrollBar(){
clearInterval(M1)
}
function ClearTimeRemovecrollBar(){
clearInterval(M2)
}**
function gettimer(){
const futureTimems = ClosingDate.getTime()
const presentTimems = new Date().getTime()
const RemainingTimeSec = (futureTimems-presentTimems)/1000
if(RemainingTimeSec>=0){
window.addEventListener('DOMContentLoaded', function(){
popup.classList.add('showpopup')
popup.classList.remove('popup')
})
}
ClosePopupBtn.addEventListener('click',function(){
popup.classList.remove('showpopup')
popup.classList.add('popup')
>setInterval containing functions working properly
**TimeShowscrollBar()
TimeRemovecrollBar()**
})
if (RemainingTimeSec<=0){
clearInterval(countdown)
>Functions with clearInterval not working here
**ClearTimeShowscrollBar()
ClearTimeRemovecrollBar()**
timing.forEach(function(contenu, MVindex){
contenu.innerHTML = '00'
})
timingS.forEach(function(contenu, MVindex){
contenu.innerHTML = '00'
})
popup.classList.remove('showpopup')
popup.classList.add('popup')
}
}
let countdown = setInterval(gettimer,1000)
gettimer()
Need do make desktop wallpaper changing software
I wanna create desktop wallpaper changing software in python. How can I do?
Everything that I want to learn with resources links.
How can I get permissions from windows.
How can I create UI.
Each steps I need.
If You recommends any courses or youtube videos, let me know
TextInput react native component rendering on web but not on Expo Go with Expo and React Native
I’m using React Native and Expo to create an android app with text fields. When I test on a web server, everything works, but not on Expo Go. Text components are in red and TextInput in blue.
Nothing in the debug DevTools of Expo Go (by pressing j).
package.json/dependencies
"dependencies": {
"@expo/webpack-config": "^18.0.1",
"@react-native-async-storage/async-storage": "^1.18.2",
"@react-navigation/bottom-tabs": "^6.5.7",
"@react-navigation/material-top-tabs": "^6.6.2",
"expo": "~48.0.18",
"expo-dev-client": "~2.2.1",
"expo-status-bar": "~1.4.4",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-native": "0.71.8",
"react-native-web": "~0.18.10",
"sass": "^1.63.3"
},
CharacterScreen.js
import { useContext, useState, useEffect } from 'react';
import { Text, View } from 'react-native';
import { TextField } from '../UI';
import { app } from '../../utils/stylesheet';
import { DataContext } from '../../utils/DataContext';
function CharacterScreen() {
const { data, setData } = useContext(DataContext)
const onLastNameChange = text => setData({ ...data, char: { ...data.char, lastName: text }})
const onNameChange = text => setData({ ...data, char: { ...data.char, name: text }})
const onBreedChange = text => setData({ ...data, char: { ...data.char, breed: text }})
const onClasseChange = text => setData({ ...data, char: { ...data.char, classe: text }})
const onCareerChange = text => setData({ ...data, char: { ...data.char, career: text }})
const onLevelChange = text => setData({ ...data, char: { ...data.char, level: text }})
const onCareerPathChange = text => setData({ ...data, char: { ...data.char, careerPath: text }})
const onStatusChange = text => setData({ ...data, char: { ...data.char, status: text }})
const onAgeChange = text => setData({ ...data, char: { ...data.char, age: text }})
const onHeightChange = text => setData({ ...data, char: { ...data.char, height: text }})
const onHairChange = text => setData({ ...data, char: { ...data.char, hair: text }})
const onEyesChange = text => setData({ ...data, char: { ...data.char, eyes: text }})
const onSTAmbChange = text => setData({ ...data, char: { ...data.char, sTAmb: text }})
const onLTAmbChange = text => setData({ ...data, char: { ...data.char, lTAmb: text }})
return (
<View style={app.screen}>
<Text style={app.title}>Informations générales</Text>
{
data ? (<>
<TextField text='Prénom' value={data.char.lastName} update={onLastNameChange} />
<TextField text='Nom' value={data.char.name} update={onNameChange} />
<TextField text='Race' value={data.char.breed} update={onBreedChange} />
<TextField text='Classe' value={data.char.classe} update={onClasseChange} />
<TextField text='Carrière' value={data.char.career} update={onCareerChange} />
<TextField text='Echelon' value={data.char.level} update={onLevelChange} />
{/* <TextField text='Schéma de carrière value={data.char.careerPath} update={onCareerPathChange} /> */}
<TextField text='Statut' value={data.char.status} update={onStatusChange} />
<TextField text='Age' value={data.char.age} update={onAgeChange} />
<TextField text='Taille' value={data.char.height} update={onHeightChange} />
<TextField text='Cheveux' value={data.char.hair} update={onHairChange} />
<TextField text='Yeux' value={data.char.eyes} update={onEyesChange} />
<TextField text='A court terme' value={data.char.sTAmb} update={onSTAmbChange} />
<TextField text='A long terme' value={data.char.lTAmb} update={onLTAmbChange} />
</>) : null
}
</View>
);
}
export default CharacterScreen;
UI.js/TextField a custom functional component that I’ve made
export function TextField({ text, value, update }) {
return (
<Text style={textField.text}>{text} : <TextInput style={textField.style} value={value} onChangeText={update} placeHolder='...' /></Text>
)
}
stylesheet.js/textField
export const textField = StyleSheet.create({
style: {
fontSize: 17,
color: 'black',
backgroundColor: 'blue'
},
text: {
fontSize: 15,
color: 'rgb(80, 80, 80)',
backgroundColor: 'red'
}
})
Nothing found on Internet about the problem …
Thanks for your help.
Discord.js : How to delete the bot/client’s message?
Basically, I want to delete the client’s message, but I don’t know how to do so. May someone help me with a code?
Here is my code:
client.on("messageCreate", (message) => {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'purge'){
message.channel.bulkDelete(args[0]);
message.channel.send(`Cleared ${args[0]} messages`)
message.delete(message.author == client)
};
});
I was trying to use the following code:
message.delete(client.message)
I am beginner to discord.js, btw.
Highlight to unknown word then context menu suggestion for that word
Type a sentence on the text area, click to highlight some unknown words, and then have a contest menu for those words
I think It is possible but it will be much more complex because each word wont be a separate element, we would need to control using the cursor position i guess. If you want to make another question with this and share the link here I can try taking a look
$("p")
.first()
.html("<span>" + text + "</span>");
const customContextMenu = $(".custom-context-menu");
const backdrop = $(".backdrop");
$("span").on("click", function (e) {
let topPosition = e.clientY;
let leftPosition = e.clientX;
customContextMenu.show();
backdrop.show();
incorrectWord = $(e.target);
customContextMenu.css("left", leftPosition + "px");
customContextMenu.css("top", topPosition + "px");
});
customContextMenu.find("li").on("click", function () {
const chosenWord = $(this).html();
incorrectWord.html(chosenWord);
customContextMenu.hide();
backdrop.hide();
});
backdrop.on("click", () => {
customContextMenu.hide();
backdrop.hide();
});
how to use slideNext/ slidePrev in react elastic caroussel
I’m using react-elastic-caroussel in my project and i want to change the position of the arrows in such way that i wouldn’t be able to do it only but changing the css, i’d have to change the html as well, since i don’t know how to do that, i thought of using the slideNext and slidePrev method described here in it’s documentation (https://sag1v.github.io/react-elastic-carousel/slideNext) so that i can just create my own buttons. The problem is, i have a functional component ad the example is using class components, i’m not very experienced with react and therefore i need help to adapt it to my code. Here’s what i have so far.
<div className={Styles.tiposDeMaquinaContent}>
<Carousel isRTL={false} breakPoints={breakPoints}>
<CarouselItem imageUrl={EscavadeiraImg}>item 1</CarouselItem>
<CarouselItem imageUrl={ManipuladorTelescopicoImg}>item 2</CarouselItem>
<CarouselItem imageUrl={MinicarregadeiraImg}>item 3</CarouselItem>
<CarouselItem imageUrl={MiniescavadeiraImg}>item 4</CarouselItem>
<CarouselItem imageUrl={RetroescavadeiraImg}>item 5</CarouselItem>
<CarouselItem imageUrl={PaCarregadeiraImg}>Pá carregadeira</CarouselItem>
</Carousel>
</div>
NextJS cors error in page but not in API route
I have a nextjs application and when I execute a call to fetch a page from an external website if I do it from the backend via an API route everything works fine however when I do it from the frontend side I get a cors error.
This is the code from the API route:
async function getPage(url: string) {
const response = await fetch(url);
// do stuff
}
export async function POST(req: any) {
const request = await req.json();
try {
await getPage(request.url);
return NextResponse.json({ status: 200 });
} catch (err: any) {
console.log(err);
return NextResponse.json({}, { status: 400, statusText: 'The website does not exist or is currently down.' });
}
}
This is the same code in the frontend that is throwing an error:
async function getPage(url: string) {
const response = await fetch(url, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*',
}
});
// do stuff
}
const fetchPageFromSite = async () => {
await getPage(url);
}
I am using the fetchPageFromSite inside a useEffect.
How do i generate ASCII visual from given JSON data in JavaScript
Is it possible to generate ASCII visual map using given JSON data using JS assuming one place can only have maximum 4 ways
something like this
A=====B======C
|
D
{
"A": [ "B"],
"B": [ "A", "C", "D"],
"C": ["D"],
"D": ["B"]
}
Below is what I tried
const data = {
"A": ["B"],
"B": ["A", "C", "D"],
"C": ["D"],
"D": ["B"]
};
for (const location in data) {
const neighbors = data[location];
let line = location;
for (const neighbor of neighbors) {
line += '=====' + neighbor;
}
console.log(line);
}
