Gets an error using the post function in firebase using react - javascript

I joined the site a few days ago.
I'm new here.
I have a problem that I can not solve. I built a function in Nodejs, every time I run the function I want to get information from the server.
On the client side I have this function, which I run, and then save the data, here no problem.
export const getRealtimeConversations = (user) => (dispatch) => {
axios.post('/realtimeConversations', user)
.then((res) => {
dispatch({
type: userConstants.GET_REALTIME_MESSAGES,
payload: res.data
});
})
.catch((err) => console.log(err))
}
I have a series of axios, when I use this line, I run a server-side function.
app.post('/realtimeConversations', FBAuth, getRealtimeConversations);
This is the function on the server side, I have a collection, which I want to access according to details I send from the client. After I have done the calculations I want, I want to return the end result.
exports.getRealtimeConversations = (req, res) => {
db.collection('conversations')
.where('user_uid_1', 'in', [req.body.uid_1, req.body.uid_2])
.orderBy('createdAt', 'asc')
.onSnapshot((querySnapshot) => {
const conversations = [];
querySnapshot.forEach(doc => {
if (
(doc.data().user_uid_1 == req.body.uid_1 && doc.data().user_uid_2 == req.body.uid_2)
||
(doc.data().user_uid_1 == req.body.uid_2 && doc.data().user_uid_2 == req.body.uid_1)
) {
conversations.push(doc.data())
}
});
console.log(conversations);
return res.json(conversations);
})
}
I do not know why but I get that I have a 404 error, I am completely new to it, I think I have a logical error in the server side function, but I'm not sure what I'm doing wrong.

Related

How to use UseEffect every time get user and axios?

I use MERN stack and redux. I have two problem and please help me.
1) Every component react I add this:
const user = useSelector( state => state.user );
useEffect( ()=>{
dispatch(User_Auth(12)) ; // I write 12 for action work.
});
I want to get user data every time if user loginned or not. Is it true? or some idea have?
2) In backend if data current I send using 200 status codes. another variant I send data other status like this:
router.get('/auth', (req, res) => {
if(req.isAuthenticated()){
req.user.isAuth = true;
res.status(200).json(req.user);
}
else{
return res.status(401).json({
isAuth: false
});
}
});
This is my action get User data:
export const User_Auth = (value) => async (dispatch) => {
value = value + 0;
await axios({
method: "GET",
url:'http://localhost:3001/api/users/auth',
withCredentials:true
})
.then(res => {
dispatch({type: user_auth, payload: res.data});
}).catch(error => {
// console.log("Auth geldim: ", error);
});
}
I want if cannot see errors in console.log browser. Can I do that?
Thanks
If you want to see the status code from an error you have to access it like this
error.status
And to get the message
error.message

JSON string sending in multiple messages. discord.js

I'm currently making a Discord bot. The code I've provided below is supposed to get data from Hypixel to display guild info. It's getting the correct info, but I want to send all the names as one message instead of one person per message.
This is my code:
const fetch = require('node-fetch');
module.exports = {
name: 'hguild',
aliases: ['hg'],
description: 'Shows info about a hypixel guild!',
guildOnly: true,
args: true,
usage: '<player>',
execute(message, args) {
var ruuid = [];
const guildName = args[0];
message.channel.send('Please wait, checking API').then((msg) => {
fetch(`https://api.hypixel.net/guild?key=[REMOVED]&name=${guildName}`)
.catch((err) => message.channel.send(err))
.then((res) => res.json())
.catch((err) => message.channel.send(err))
.then((json) => {
console.log(json);
msg.edit('Here is about your guild!');
for (const guild of json.guild.members) {
const rawUsername = guild.uuid;
fetch(`https://api.mojang.com/user/profiles/${rawUsername}/names`)
.catch((err) => message.channel.send(err))
.then((res) => res.json())
.catch((err) => message.channel.send(err))
.then((json) => {
console.log(json[0].name);
if (json.name == null || json.status == 'ERR') {
}
var testList = [json[0].name];
message.channel.send(testList);
});
}
});
});
},
};
Currently its showing all the names, but sends one name per message. I want to group all these names together.
Instead of executing these two lines:
var testList = [json[0].name];
message.channel.send(testList);
And then closing the for loop, try pushing the results to an array initialized before the loop, then send that. Example:
var testList = [];
const getUsernames = async () => {
for await (const guild of json.guild.members) {
const rawUsername = guild.uuid;
fetch(`https://api.mojang.com/user/profiles/${rawUsername}/names`)
.catch((err) => message.channel.send(err))
.then((res) => res.json())
.catch((err) => message.channel.send(err))
.then((json) => {
console.log(json[0].name);
if (json.name == null || json.status == 'ERR') {
}
testList.push(json[0].name);
});
}
};
await getUsernames();
message.channel.send(testList.join('\n'));
Make sure you change the execute(message, args) line at the top of your code to async execute(message, args) so that await is possible.
As a disclaimer, I am not knowledgable in the Minecraft API area, and do not know how the object returned from your request is structured. This is just my best guess.
#Lioness100 Also unfamiliar with the Minecraft API.
I'm curious about the loop, seems like your initial fetch to the api with guild info returns what you're looking for.
Are you deconstructing names to test the functionality to eventually push entire profiles to discord? or are you content with just names?
(For the latter, instead of the loop have you tried)
message.channel.send(json.guild.members)
Otherwise another thing to consider would be utilizing the loop to generate an array of URLs that you could resolve together with a Promise.all. Wondering if the undesired output is a result of asynchronous behavior. Here's the api docs for reference:
https://javascript.info/promise-api
Hope that works, friend!

Telegram Bot API: Server down when use getUserProfilePhotos()

Context
I am using telegraf.js for more than 3 bots which run very well in plenty of groups.
Currently one of the bots needs to request for Display Picture of the user who does not have a display picture.
It works very well as expected but unfortunately the bot throws an error and the server goes down
Current Code
// Request for display picture
const requestDP = async (ctx, next) => {
const { from, chat } = ctx.message;
const { can_delete_messages:canDelete } = await deletePermision(ctx);
let totalDPs = 1;
totalDPs = await ctx.telegram.getUserProfilePhotos(ctx.message.from.id)
.then((result) => result.total_count)
.catch((err) => {
console.log(err);
});
if (totalDPs != 0) return next();
if ((chat.id === -1001341734527 || chat.id === -1001083711103 ) && canDelete) {
await ctx.deleteMessage().then((response) => response, ({ response }) => response.ok);
await ctx.replyWithMarkdown(`[${from.first_name||''} ${from.last_name||''}](tg://user?id=${from.id}), പ്രൊഫൈൽ ഫോട്ടോ ഇല്ലാത്തവർക്ക് ഗ്രൂപിൽ മെസേജ് അയക്കാൻ സാധ്യമല്ല`)
.then(({ message_id }) => setTimeout(() => ctx.deleteMessage(message_id), 5 * 60 * 1000))
.catch((err) => console.log("Error in prevencontacts: " + err));
}
}
module.exports = requestDP;
Failure Information (for bugs)
let totalDPs = 1;
totalDPs = await ctx.telegram.getUserProfilePhotos(ctx.message.from.id)
.then((result) => result.total_count)
.catch((err) => {
console.log(err);
});
The functions seem to be working well. But unfortunately sometimes they get an error the and server goes down.
Error message 👇
Error: 400: Bad Request: request for new profile photos has already been sent
It is really hard to refresh the server occasionally :-(
Is there any solution to manage this error ?

How do I pass a react DOM state's information to backend(NodeJS) when a button is invoked?

I'm using his logic on the frontend, but I'm having some trouble actually receiving that data on the backend. I'm using the Sails.js framework. Any suggestions?
handleSubmit = () => {
// Gathering together the data you want to send to API
const payload = {
subject: this.state.subject,
message: this.state.message,
};
this.handleAjaxRequest(payload);
};
// Method to send data to the backend
// Making the req -I'm using Axios here.
handleAjaxRequest = (payload) => {
let request = axios({
method: 'post',
url: '/api/',
data: payload,
headers: 'Content-Type: application/json'
});
// Do stuff with the response from your backend.
request.then(response => {
console.debug(response.data);
})
.catch(error => {
console.error(error);
})
};
I used to do this using Express and didn't have these problems.
Any help, method, a suggestion is more than welcome :)
Please forgive my ignorance, I'm just here to learn.
Okay, so the first thing I had to do is generate a new restful API using the command sails generate api data. In the package.json file I set up a proxy that includes the backends endpoint, like this "proxy": "http://localhost:1337" - I mean, you don't need to do this, but if you don't then you have to include this URL part on every request. Because it doesn't change, it's pretty convenient to do so.
On the frontend, I made a function sendData() that takes the necessary data from my previous component (depending on what the user selected) and send that data using axios to the backend -->
sendData = () => {
const { relYear } = this.props.history.location.state.dev;
const { relMonth } = this.props.history.location.state.dev;
const selectedMonth = moment().month(relMonth).format("MM");
const finalSelect = parseInt(relYear + selectedMonth, 10);
axios.post('/data', { 'selectedDate' : finalSelect })
.then(res => console.log('Data send'))
.catch(err => console.error(err));
}
On the backend I fetched the data, did the calculations and send back the result to the frontend of my app. -->
getApiData = () => {
let apiData = [];
axios.get('/data')
.then(res => {
let first = Object.values(res.data.pop()).shift(); // Getting the relevant 'selectedDate'
apiData.push(first);
}).catch(err => console.error(err));
return apiData;
}

firebase.auth().signInWithPhoneNumber + express on Node.js

I've got a trouble when trying to implement backend firebase Authorization.
After I had read carefully the docs (https://firebase.google.com/docs/auth/web/phone-auth), I figured out that Authorization need to be proceded by two steps:
send phone
send code
I divided Google's example on two promises, but can't understand how to store current user and whether or not I've done everything in an appropriate way.
app.post("/appSignInByPhone", (req, res) => {
let {phoneNumber, applicationVerifier} = req.body;
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then(() => res.end("Waiting for code"))
.catch(
error => res.json(error)
);
});
app.post("/appSignInPhoneVerify", (req, res) => {
let {verificationCode} = req.body;
firebase.auth.ConfirmationResult.confirm(verificationCode)
.then( user => res.json(user))
.catch(
error => res.json(error)
);
});
Maybe there are some ways of merging these to request to one...
Try the following:
In step #1 either store or send back the confirmationResult you get from the fulfillment handler:
firebase.auth().signInWithPhoneNumber(phoneNumber, applicationVerifier)
.then((confirmationResult) => {
// either store confirmationResult
// or send it to the client and ask for it in step #2)
}).catch(
error => res.json(error)
);
then in step #2:
// get the confirmationResult from the client or from some storage
// in the server
// for example let { verificationCode, confirmationResult } = req.body;
confirmationResult.confirm(verificationCode)
.then( user => res.json(user))
.catch(
error => res.json(error)
);

Categories