copy to clipboard for each list - javascript

i've got two list black and white numbers in JS Vue
for each one i made a button when i click on it the related numbers of list copy to clipboard
but only my white list copy to clipboard...any idea?
const copyClipBoard = (isWhite) => {
let params;
if (isWhite) params = selectedFiltersWhite.filters;
else params = selectedFiltersBlack.filters;
const data = { filter: { filters: params } };
const token = settings.get("token");
const baseUrl = import.meta.env.VUE_APP_SERVER;
axios({
method: "get",
url: baseUrl + `api/v1/user/check-blacklist/`,
params: data,
headers: { Authorization: "Bearer " + token }
}).then((res) => {
const array: any = [];
res.data.data.items.forEach((el: any) => {
array.push(el.number);
navigator.clipboard.writeText(array);
});
message.success("copeid");
}).catch(error => {
message.error("something went worng");
console.log(error);
});
};

Related

Postman Pre-request script for Token

I try to write Pre-script for auto-refresh for token before any request. I know about async, but for first two pm.sendRequest everything is okey, but last pm.sendRequest failed for some reason with error "unauthorised". But Activation token from jsonResponseActivationToken is on their place.
const newActivationRequest = {
method: 'POST',
url: newActivationUrl,
body: {
}
};
const activationTokenRequest = {
method: 'POST',
url: activationTokenUrl,
body: {
}
};
const sessionTokenRequest = {
method: 'POST',
url: sessionTokenUrl,
body: {
}
};
pm.sendRequest(newActivationRequest, (err, responseNewActivation) => {
const jsonResponseNewActivation = responseNewActivation.json();
const statusNewActivation = jsonResponseNewActivation.status;
if(statusNewActivation === 'SUCCESS'){
pm.sendRequest(activationTokenRequest, (err, responseActivationToken) => {
const jsonResponseActivationToken = responseActivationToken.json();
const statusTokenRequest = jsonResponseActivationToken.status;
if(statusTokenRequest === 'SUCCESS'){
const newAccessToken = jsonResponseActivationToken.access_token;
pm.collectionVariables.set('token', newAccessToken);
pm.sendRequest(sessionTokenRequest, (err, responseSessionToken) => {
const jsonResponseSessionToken = responseSessionToken.json();
const statusSessionToken = jsonResponseSessionToken.status;
console.log('8');
if(statusSessionToken === 'SUCCESS'){
const newSessionToken = jsonResponseSessionToken.access_token;
pm.collectionVariables.set('token', newSessionToken);
}
});
}
});
}
});

POST request called twice given callback

I have some code in TypeScript to process Spotify's login flow, it looks like this:
import * as React from 'react';
import '#patternfly/react-core/dist/styles/base.css';
import { useNavigate } from "react-router-dom";
import env from "ts-react-dotenv";
interface Props {
token: string;
}
const Callback: React.FC<Props> = (props: Props) => {
const { token } = props;
const searchParams = new URLSearchParams(token);
const code = searchParams.get('code');
var accessToken = '';
// Create the POST request to get the access token
const data = {
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:3000/callback',
};
const body = new URLSearchParams();
for (const [key, value] of Object.entries(data)) {
if (value){
body.append(key, value);
}
}
const request = new Request('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + btoa(env.CLIENT_ID + ':' + env.CLIENT_SECRET),
},
body: body,
});
// Send the POST request
fetch(request)
.then((response) => response.json())
.then((data) => {
console.log("Access token: " + data.access_token);
if (accessToken){
accessToken = data.access_token;
}
});
// Navigate to Home with the code
// https://github.com/react-navigation/react-navigation/issues/10803
// Redirect to Home
const navigate = useNavigate();
setTimeout(() => navigate('/home', { state: { accessToken } }), 50);
return <div>Loading... if the app doesn't work please reload</div>;
};
export default Callback;
I see that in the console there are 2 calls, the first one produces the correct result while there is somehow a second call that seems like its being made. I suspect that my post request somehow triggered another call within the callback field but I am not sure how that happened.
How can I fix this, set the correct access_token and go to the next page?
You need to put the fetch call inside a useEffect hook, with dependency array as empty, Please refer useEffect
When we run the code on local server there component will be render at least 2 time, since CRA will create the code with strict mode.
import * as React from "react";
import "#patternfly/react-core/dist/styles/base.css";
import { useNavigate } from "react-router-dom";
import env from "ts-react-dotenv";
interface Props {
token: string;
}
const Callback: React.FC<Props> = (props: Props) => {
const { token } = props;
const searchParams = new URLSearchParams(token);
const code = searchParams.get("code");
var accessToken = "";
// Create the POST request to get the access token
const data = {
grant_type: "authorization_code",
code: code,
redirect_uri: "http://localhost:3000/callback",
};
const body = new URLSearchParams();
for (const [key, value] of Object.entries(data)) {
if (value) {
body.append(key, value);
}
}
const request = new Request("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Basic " + btoa(env.CLIENT_ID + ":" + env.CLIENT_SECRET),
},
body: body,
});
// Send the POST request
useEffect(() => {
fetch(request)
.then((response) => response.json())
.then((data) => {
console.log("Access token: " + data.access_token);
if (accessToken) {
accessToken = data.access_token;
}
});
}, []);
// Navigate to Home with the code
// https://github.com/react-navigation/react-navigation/issues/10803
// Redirect to Home
const navigate = useNavigate();
setTimeout(() => navigate("/home", { state: { accessToken } }), 50);
return <div>Loading... if the app doesn't work please reload</div>;
};
export default Callback;

While sending courses to backend api, it is coming in loop for many times

I have a frontend on vanilla JS, In which i am taking some courses from user and sending them to my backend api but it takes first course for two time and when i select more than 2 courses it repeates first course for two times, second for one and third for three times, I I have tried different things but it didn't work. Can somebody please guide me on this?
let courseList1 = []
let courseList = []
addCoursesBtn.addEventListener('click', () => {
courseList1.push(dropdownCourses.value)
// appending on frontend
let value = courseList1[courseList1.length - 1];
courseContainer.append(value)
courseList1.forEach((course, index) => {
console.log("inside for each")
let mappedValue = {
courseName: course
};
courseList.push(mappedValue)
console.log("course list is: " + courseList)
})
})
form.addEventListener('submit', async function (e) {
try {
e.preventDefault();
let token = localStorage.getItem("Token")
let name = inputName.value;
let phoneNumber = inputPhoneNum.value;
let cnic = inputCnic.value;
const body = {
name, phoneNumber, cnic, courseList
}
console.log(body)
const response = await fetch("http://localhost:8080/addStudent", {
method: "PUT",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${token}`
},
body: JSON.stringify(body)
})
const res = await response.json();
console.log(res);
} catch (error) {
console.log(error);
}
});

LinkedIn Posts API response is OK but post not showing

This issue only occurs with posts with multipart video, Posts with images and videos below 4MB are working, when posting to Posts API i get a response with Status OK and the post URN in the header but when i try getting the post data using the given URN i'm getting error 404.
Here is the function that i am using to upload the video to LinkedIn.
const uploadVideo = async (linkedinId, accessToken, videoUrl) => {
/* Fetching video from Google storage */
const videoData = await axios.get(videoUrl, { responseType: 'arraybuffer' });
const contentType = videoData.headers['content-type'];
const videoSize = videoData.headers['content-length'];
const url = 'https://api.linkedin.com/rest/videos';
const body = {
initializeUploadRequest: {
owner: `urn:li:organization:${linkedinId}`,
fileSizeBytes: Number(videoSize),
},
};
const headers = {
Authorization: `Bearer ${accessToken}`,
'X-Restli-Protocol-Version': '2.0.0',
'x-li-format': 'json',
'LinkedIn-Version': 202207,
};
const response = await axios.post(url, body, { headers, params: { action: 'initializeUpload' } });
const { uploadInstructions } = response.data.value;
const asset = response.data.value.video;
/* Uploading video */
try {
const uploadPromises = uploadInstructions.map(async ({ uploadUrl, firstByte, lastByte }) => {
const arrayBuffer = videoData.data.slice(firstByte, lastByte);
return axios({
url: uploadUrl,
method: 'POST',
data: arrayBuffer,
headers: {
'Content-Type': contentType,
},
maxBodyLength: Infinity,
maxContentLength: Infinity,
});
});
const uploadResponses = await Promise.all(uploadPromises);
const finalizeUploadBody = {
finalizeUploadRequest: {
video: asset,
uploadToken: '',
uploadedPartIds: uploadResponses.map((uploadResponse) => uploadResponse.headers.etag),
},
};
await axios.post(url, finalizeUploadBody, {
headers: {
...headers,
'Content-Type': 'application/json',
},
params: {
action: 'finalizeUpload',
},
});
} catch (error) {
throw error;
}
return asset;
};
Here is the function that i am using to publish the post to LinkedIn.
const publishContent = async (
linkedinId,
accessToken,
media,
) => {
const url = 'https://api.linkedin.com/rest/posts';
const body = {
author: `urn:li:organization:${linkedinId}`,
commentary: 'content',
visibility: 'PUBLIC',
lifecycleState: 'PUBLISHED',
distribution: {
feedDistribution: 'MAIN_FEED',
},
};
const asset = await uploadVideo(linkedinId, accessToken, media.urls[0], isPage);
body.content = {
media: {
title: 'Title',
id: asset,
},
};
const headers = {
Authorization: 'Bearer ' + accessToken,
'X-Restli-Protocol-Version': '2.0.0',
'x-li-format': 'json',
'LinkedIn-Version': 202207,
};
return axios.post(url, body, { headers });
};

Trying to dynamically set .find() parameters from client input - mongodb:Atlas

I am trying to use data from the client, which they would type into an input box. The idea is to use this for finding in my database to pull the data with the same username. on my Mongo DB:Atlas collection.
So its to use it like this to get the names from the database, .find({"username": request.body})
However, I keep getting the error "CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1" on my terminal.
But when I try to hard code it onto the .find({"username": "name"), it works fine. Does anyone have any ideas?
**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
Actually, you're passing the object {username : "value"} to the find method. You need to pass the string.
app.post('/database', (request,response) => {
const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

Categories

Resources