Why im getting this error invalid Payload? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
import admin from "firebase-admin";
async function notifyUser(message ,title, photoURL,token , uid , notificationsOn ) {
const messages = [];
const payload = {
notification: {
title: title,
body: message,
},
data: {
uid,
},
android: {
notification: {
image: photoURL,
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: photoURL,
},
},
};
try {
if (token) {
messages.push({ token: token, ...payload });
console.log("yes");
}
if (messages.length && notificationsOn==true) {
await admin.messaging().sendAll(messages);
console.log("Token for user, send notification.");
}
} catch (error) {
const functions = require("firebase-functions");
functions.logger.log("Hello from info. Here's an object:", error);
console.log(photoURL);
console.log(notificationsOn);
console.log(token);
console.log(message);
console.log(uid);
console.log(title)
console.log("No token for user, can not send notification.");
return {error:error.code};
}
return;
};
export {notifyUser} ;
The error I get
The line 169 is this line
await admin.messaging().sendAll(messages);
It's always logging "No token for user cannot send notification". And I don't have any idea why. I checked like 30 times. The logs are not empty and give the correct output. The token is not empty.
It's not working on both android and iOS. But when sending notification via firebase to android or iOS it works. And notification retrieved .
Hope really anyone has and idea. I also tried to send notification from firebase via token. This also works . And as I said I checked every output it should work but does not.
If you think I did something wrong in configuration in my project please tell me what I you think it can be .

comes out that adding this statement
token:token like this
const payload = {
notification: {
title: title,
body: message,
},
token: token,
data: {
uid,
},
android: {
notification: {
image: photoURL,
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: photoURL,
},
},
};
into payload but outside of all other statements fixed the issue.

Related

Is there any way to display data from Firebase Firestore as a React Table? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
Is it possible to display data from Firebase Firestore in a React Table?
I tried several approaches, but none worked. I tried map function and listing them by creating a custom React element by providing the data using props.
Expectation:
My Expectation
I want to display the user email, UID, and password as a table.
My Code:
let data = [];
// creating an user
const createUser = () => {
let email = prompt("Enter the user's email: ");
let password = prompt("Enter the user's password: ");
let collectionName = `${window.localStorage.getItem("user-email")}_auth-details#BESTCLOUD`;
password = MD5(password);
db.collection(collectionName).add({
email: email,
password: password
}).then(function (docRef) {
alert("Successfully created!")
console.log("UID", docRef.id);
db.collection(`${window.localStorage.getItem("user-email")}_auth-details#BESTCLOUD`).onSnapshot((snapshot) => {
let x = snapshot.docs.map((doc) => ({
id: doc.id,
data: doc.data(),
}))
for (let i = 0; i < 5; i++) {
data.push({
email: x[i].data.email,
id: x[i].id,
num: i
});
console.log(data)
}
});
})
.catch(function (error) {
console.error("Error: ", error);
});
};
If I do this, data is
[
{
"id": "fMrLCDCkUqsV8BcoFcNY",
"data": {
"email": "peter123#gmail.com",
"password": "e7e761c4d399a441c6469a7c0626ac2d"
}
}
]

How do I send data to express backend from html frontend without a form?

I am trying to create a small ecommerce website where I need to have a cart page. I need to make it so when a user clicks on Add to cart button, the particular item will get sent to the backend and stored in the cart collection.
What I'm having trouble with is that when I click the add to card button and the function linked to it runs, I get an error stating : SyntaxError: Unexpected token " in JSON at position 0
Here's my function which is supposed to send data to the backend:
let addToCart = async (item) => {
// item is the object I get which contains all the information I need
try {
let product = item._id;
await fetch('http://localhost:5000/cart', {
method: 'post',
body: product,
headers: {
'Content-Type': 'application/json',
},
});
} catch (e) {
console.log({error : e});
}
};
This is my cart model :
const cartSchema = new mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
required: true,
},
cartProducts: {
type: Array
},
},
{
versionKey: false,
timestamps: true,
}
);
This is my cart controller POST CRUD
router.post('', authenticate, async (req, res) => {
const user = req.user;
console.log(user);`
try {
const cart = await Cart.findOneAndUpdate(
{ userId: user._id },
{
$push: {
cartProducts: req.body,
},
},
{ new: true, upsert: true }
);
return res.status(200).send(cart);
} catch (err) {
return res.status(400).send({ message: err.message });
}
});
I am able to get user using authenticate middleware.
I can post everything using Postman but I can't figure how to get rid of the Syntax error.
When I console.log typeof item, I get an object. Product's type is string. I have also tried using JSON.stringify but nothing seems to be working. I have also tried using bodyparser middleware.

Persisting Error - "Parse Error: Header overflow"

I am working on a Next.js project, in which I have included a login system with NextAuth.
Everything was working fine at the beginning, but recently I keep getting an error every time I try to get the session.
The Error:
https://pastebin.com/Mh624N3c
StackOverflow doesn't let me post the whole error, so I had to use Pastebin.
This is the first time I encounter such an error, and I can't seem to be able to find a solution. I am using JWT as the session strategy, if that has to do anything with the issue.
This is the code I use for handling the authentication & session:
await NextAuth(req, res, {
adapter: MongoDBAdapter(clientPromise),
pages: {
signIn: "/login"
},
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email", placeholder: "example#email.com" },
password: { label: "Password", type: "password" }
},
async authorize(credentials, req) {
const account = await Accounts.exists(credentials.email)
const cryptr = new Cryptr(Config.secret)
const encEmail = cryptr.encrypt(credentials.email)
const url = process.env.NODE_ENV == "development" ? "http://localhost:3000/" : Config.url
if (account) {
const password = cryptr.decrypt(account.password)
if (credentials.password == password) {
return {
...account,
_id: null
}
} else {
return res.redirect("/login?error=true")
}
} else {
const code = await Accounts.requestVerification(credentials.email, password)
const message = {
to: credentials.email,
from: "noreply#bytestobits.dev",
subject: "BytesToBits API - Create Your Account",
html: emailStyle(credentials?.email, url, code),
}
SendGrid.send(message).then(() => console.log("Email Sent"))
return res.redirect("/verify?email=" + encEmail)
}
}
})
],
jwt: {
secret: Config.secret,
encryption: true
},
secret: Config.secret,
session: {
strategy: "jwt"
},
callbacks: {
async jwt({ token, user }) {
if (user) {
token.user = user
}
return token
},
async session({ session, token }) {
let data = token.user
if (data) {
if (await Accounts.exists(data.email)) {
data.token = await Accounts.getToken(data.email)
}
data.tokenInfo = await Accounts.tokenInfo(data.token)
}
return data
}
}
})
This happens every time I try to fetch the session or authenticate.
When the user authenticates, a session must be formed, which can be fetched from the client for usage. However, whenever I try to authenticate of fetch the session, a "Parse Error: Header overflow" occurs.
I managed to fix the issue! Turns out the Session object was way too long and caused this error.
Basically in the data's tokenInfo field, it had a really long array. So removing that specific field fixed the issue!

Can't send Kafka messages though topic and producer both exist

I'm working in TypeScript with the KafkaJS library locally, with a single kafka broker. I've connected a producer successfully, have verified that my topic was created, and am generating messages with:
const changeMessage = {
key: id,
value: JSON.stringify(person),
headers: {
changeType: status,
},
};
Now when I go to send the message:
try {
const sendResponse = await producer.send({
topic: topicName2,
messages: [changeMessage],
});
log.responseFragment(
{ id, topicName2 },
`Sending changed/added person ${id} to topic ${topicName2}`
);
} catch (error) {
log.error(
{ error }, `Could not send personChangedAdded ${id} to topic ${topicName2}`
);
}
Here's the error that I get back:
Could not send personChange to topic topicName2
error: {
"name": "KafkaJSError",
"retriable": true
}
I had failed to define log.responseFragment(), and when I changed it to a simple log.info() the problem was resolved.

How to check if there are no more documents to update using findOneAndUpdate

So I am learning CRUD for a school project and I followed a tutorial that was really useful. However, when I completed it I noticed that when there are no more quotes to update, it still updates quotes. How can I change this so that it will stop updating quotes that arent even there?
app.put('/quotes', (req, res) => {
quoteCollection.findOneAndUpdate(
{ name: 'Yoda' },
{
$set: {
name: req.body.name,
quote: req.body.quote
}
},
{upsert: true}
)
.then(result => {
//The if block that i am trying
if (result.deletedCount === 0) {
return res.json('No quote to delete')
}
})
.catch(error => console.error(error))
})
Why are you passing {name: "Yoda}? This route is supposed to only update the quote with "Yoda" as its name? If not, then you need to grab from the request object the quote that should be updated.
I tried to create a different version, based on the assumption that the quote that should be updated will come from the req.body:
app.put("/quotes", async (req, res) => {
//Grab the name/id/identifier for the quote you want to update from the body
const query = req.body.name;
// Try to update the document on the database
try {
const result = await quoteCollection.findOneAndUpdate(
query,
{
name: req.body.name,
quote: req.body.quote,
},
{
upsert: true,
new: true,
}
);
// If it worked, it will return the updated quote
res.status(200).json({
status: 200,
data: {
result,
},
});
} catch (err) {
res.status(400).json({
status: 400,
message: "Something went wrong",
});
}
});

Categories