how can we store the response to local storage which comes from post api in NEXT.JS - mongodb

Here is my post function which is posting data
const submitHandler = async (e) => {
e.preventDefault();
setLoading(true);
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
toast.warning("Please Fill all the Fields", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "light",
bodyClassName: 'font-bold'
});
setTimeout(() => {
setLoading(false)
}, 2000);
return;
}
if (password !== confirmpassword) {
toast.warning("Passwords not Matched", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "light",
});
setTimeout(() => {
setLoading(false)
}, 2000);
return;
}
try {
const config = {
headers: {
"Content-type":"application/json"
}
}
const { dev } = await axios.post("/api/registerteacher", {
name,
phone,
email,
gender,
password,
confirmpassword,
pic,
},config);
toast.success("Registration Succesfull", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "dark",
});
console.log(dev)
localStorage.setItem("teacherinfo", JSON.stringify(dev));
setLoading(false);
router.replace("/teacher/selectcategory");
} catch (error) {
toast.error("Error Occured, Try Again Later", {
position: "bottom-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
progress: undefined,
theme: "dark",
className:"rounded-full"
});
setLoading(true);
}
};
In the above function I am taking the data from the register page. data is name, email, phone, password and confirm password and there are some validations at the front end and if data is not validate the showing the toast by react toastify and after vaidation i am posting the data to the backend by axios and storing the response in dev variable and store the dev variable in localstorage but i am getting the dev as undefined from the backend.
Here my backend code looks like:
import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;import generateTeacherToken from './tokens/generateTeacherToken';
require('./db/regg')
const TeacherSchema = require('./models/teacherSchema')
const handler = async(req, res) => {
if(req.method === 'POST'){
const { name, email, phone, gender, password, confirmpassword, pic} = req.body;
if (!name || !email || !phone || !gender || !password || !confirmpassword) {
throw new Error('Please Fill all fields');
}
const userExists = await TeacherSchema.findOne({ email });
if (userExists) {
res.status(400)
throw new Error('User already exists');
}
const teacher = await TeacherSchema.create({
name,
email,
phone,
gender,
password,
confirmpassword,
pic,
});
if (teacher) {
res.status(201).json({
_id : teacher._id,
name : teacher.name,
email : teacher.email,
phone : teacher.phone,
gender : teacher.gender,
pic : teacher.pic,
token : generateTeacherToken(teacher._id),
});
}else{
res.status(400);
throw new Error("Failed to create the teacher")
}
}
}
export default handler;
In backend the frontend data is storing in mongo db and send the respone too. but still the dev is undefined.
Here is my respone looks like
{
"_id": "63c8085ed8a4774dc48c68c6",
"name": "joe don",
"email": "john#gmail.com",
"phone": "6350330324",
"pic": "https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYzYzgwODVlZDhhNDc3NGRjNDhjNjhjNiIsImlhdCI6MTY3NDA1MzczMiwiZXhwIjoxNjc2NjQ1NzMyfQ.ejS4PlsmQhS4Avu8Vo6B7RmuEhlhhGI2hPRRwQRCsyE"
}
Please Help me I am Stucked in this problem
How can i store the response (dev) in localstorge to use for put request

Related

I am working with stream signup is working with status 200 but did not create user in stream

const handleSubmit = async (e) => {
e.preventDefault();
const { username, password, phoneNumber, avatarURL } = form;
const URL = 'http://localhost:5000/auth';
const { data: { token, userId, hashedPassword, fullName } } = await axios.post(`${URL}/${isSignup ? 'signup' : 'login'}`, {
username, password, fullName: form.fu
llName, phoneNumber, avatarURL,
});

The client_secret Provided does not match any associated PaymentIntent on this account

I'm trying to use flutter_stripe for a stripe connect account, But I always get the
same error: The client_secret provided doesn't match the client_secret associated with the PaymentIntend.
I've completed all steps according to flutter_stripe but I still face this error.
Below is my code Please check this and help me.
inde.js
const functions = require("firebase-functions");
const stripe = require("stripe")("secret_key");
exports.stripePaymentIntentRequest = functions.https.onRequest(async (req, res) => {
try {
let customerId;
//Gets the customer who's email id matches the one sent by the client
const customerList = await stripe.customers.list({
email: req.body.email,
limit: 1
});
//Checks the if the customer exists, if not creates a new customer
if (customerList.data.length !== 0) {
customerId = customerList.data[0].id;
}
else {
const customer = await stripe.customers.create({
email: req.body.email
});
customerId = customer.data.id;
}
//Creates a temporary secret key linked with the customer
const ephemeralKey = await stripe.ephemeralKeys.create(
{ customer: customerId },
{ apiVersion: '2020-08-27' }
);
//Creates a new payment intent with amount passed in from the client
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(req.body.amount),
currency: 'usd',
customer: customerId,
})
res.status(200).send({
clientSecret: paymentIntent.client_secret,
paymentIntent: paymentIntent,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
})
} catch (error) {
res.status(404).send({ success: false, error: error.message })
}
});
PaymentService.dart
Future<void> initPaymentSheet(
{required BuildContext context, required String email, required int amount}) async {
try {
// 1. create payment intent on the server
final response = await http.post(
Uri.parse(
'Firebase api link of Functions'),
body: {
'email': email,
'amount': amount.toString(),
});
Map<String, dynamic> paymentIntentBody = jsonDecode(response.body);
log(paymentIntentBody.toString());
//2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
merchantDisplayName: 'Flutter Stripe Store Demo',
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
style: ThemeMode.light,
testEnv: true,
merchantCountryCode: 'US',
),
);
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Payment completed!')),
);
} catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error the Stripe of : $e')),
);
}
}
}
The log error print on my console is :
> [log] {paymentIntent:
> pi_3LI2acCTAUDjRNFV1Ra3dahz_secret_Fcqw73pWrE4avKRyuDVzRBitG,
> ephemeralKey:
> ek_test_YWNjdF8xSlQ3amtDVEFVRGpSTkZWLDl1OE5Vdm1jTGY4T1RpaVhHOTB3NTRVSkQ5UGl4azA_00j32OYG9n,
> customer: cus_LHG2YpQP9Cgwuy, success: true}
The following code is from a previous Stripe evaluation stage. But it worked. Slim it down to your needs.
Remember to publish your secret key to the server, so the server can talk to Stripe.
code.dart
Future<bool> payWithPaymentSheet(
ProductModel productModel, PriceModel priceModel,
{String merchantCountryCode = 'DE'}) async {
if (kIsWeb) {
throw 'Implementation not availabe on Flutter-WEB!';
}
String uid = AuthService.instance.currentUser().uid;
String email = AuthService.instance.currentUser().email ?? '';
HttpsCallableResult response;
try {
response = await FirebaseFunctions
.httpsCallable('createPaymentIntent')
.call(<String, dynamic>{
'amount': priceModel.unitAmount,
'currency': priceModel.currency,
'receipt_email': email,
'metadata': {
'product_id': productModel.id,
'user_id': uid,
"valid_until": productModel.getUntilDateTime().toIso8601String(),
'product_name': productModel.name.tr,
},
'testEnv': kDebugMode,
});
} on FirebaseFunctionsException catch (error) {
log(error.code);
log(error.details);
log(error.message ?? '(no message)');
Get.snackbar(
error.code,
error.message ?? '(no message)',
icon: const Icon(Icons.error_outline),
);
return false;
}
Map<String, dynamic> paymentIntentBody = response.data;
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
currencyCode: priceModel.currency,
applePay: false,
googlePay: false,
merchantCountryCode: merchantCountryCode,
merchantDisplayName: Strings.appName,
testEnv: kDebugMode,
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
));
try {
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
log(e.error.code.name);
log(e.error.message ?? '(no message)');
log(e.error.localizedMessage ?? '(no message)');
Get.snackbar(e.error.code.name, e.error.message ?? '',
icon: const Icon(Icons.error_outline));
} catch (e) {
Get.snackbar('An unforseen error occured', e.toString(),
icon: const Icon(Icons.error_outline));
}
return false;
}
index.ts
// SETTING SECRET KEY ON SERVER:
// cd functions
// firebase functions:config:set stripe.secret_key="sk_live_51L...Noe"
// firebase deploy --only functions
let stripe = require("stripe")(functions.config().stripe.secret_key);
exports.createPaymentIntent = functions
.https.onCall((data, context) => {
// if (!context.auth) {
// return { "access": false };
// }
return new Promise(function (resolve, reject) {
stripe.paymentIntents.create({
amount: data.amount,
currency: data.currency,
receipt_email: decodeURIComponent(data.receipt_email),
metadata: data.metadata,
}, function (err, paymentIntent) {
if (err != null) {
functions.logger.error("Error paymentIntent: ", err);
reject(err);
}
else {
resolve({
clientSecret: paymentIntent.client_secret,
paymentIntentData: paymentIntent,
});
}
});
});
});

I can't update a users info to add a password reset link

I'm having trouble getting a variable within a database user to update using lodash. It seems to update in one route (password in /resetpassword) but not in the other. (resetLink in /forgotpassword)
I need to have "resetLink" update to the new token generated by JWT, in order to create a link to reset the users password.
/forgotpassword
router.put('/forgotpassword', (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ msg: "Please enter all fields" });
} else {
// Find existing User by email address
User.findOne({ email }).then((user) => {
if (!user) return res.status(400).json({ msg: "That email doesn't exist with us..." });
const payload = {
id: user._id,
}
const secret = process.env.JWT_SECRET;
const token = jwt.sign(payload, secret, {
expiresIn: '15m'
});
const obj = {
resetLink: token
}
console.log("obj is " + JSON.stringify(obj));
console.log("User is " + user);
user = _.extend(user, obj);
user.save((err, result) => {
if (err) {
return res.status(400).json({{ error: "Something went wrong..." + err }});
} else {
return res.status(200).json({ msg: "Success! These should match: TOKEN - " + token + " / RESET LINK - " + user.resetLink })
}
})
});
};
});
/resetpassword
router.put('/resetpassword', (req, res) => {
const { resetLink, newPass } = req.body;
if (resetLink) {
jwt.verify(resetLink, process.env.JWT_SECRET, function (err, decodedData) {
if (err) {
return res.status(401).json({ msg: "Incorrect token or it is expired." });
}
User.findOne({ resetLink }, (err, user) => {
if (err || !user) {
return res.status(400).json({ error: "User with this token doesn't exist" });
}
// newPass will be hashed by jwt eventually
const obj = {
password: newPass
}
user = _.extend(user, obj);
user.save((err, result) => {
if (err) {
return res.status(400).json({ error: "Reset password error" });
} else {
return res.status(200).json({ message: "Your password has been changed" });
}
})
})
})
} else {
return res.status(401).json({ error: "Authentication error!" });
}
});
Mongoose User model
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
},
password: {
type: String,
required: true,
},
register_date: {
type: Date,
default: Date.now,
},
resetLink: {
data: String,
default: '',
}
});
As always I appreciate any help at all. Thanks.
EDIT: Here is the returned error -
"error": "Something went wrong...ValidationError: resetLink: Cast to Object failed for value \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmM2JjN2MwNGVmMmRkNGE2ODkwZDEwYiIsImlhdCI6MTU5Nzc1NDY2MCwiZXhwIjoxNTk3NzU1NTYwfQ.BL8yYsqk2A5hGlNTPa2AxtD_iJ1lWELiCgtpcCkFB6I\" at path \"resetLink\""
My Schema was off. Apologies.
resetLink: {
data: String,
default: '',
}
Should be:
resetLink: {
Type: String,
default: '',
}

MongoDB: No write concern mode named 'majority a' found in replica set configuration

I am working through a traversy media tutorial and I've come across an error (in the title) that I'm not familiar with. I've been trying to learn about this but I'm still stumped as to why its appearing and where its coming from. Furthermore, I havent found any direct matches for this issue.
Here is the code in question, the catch at the bottom is returning the error.message.
edit: its also worth noting that I am able to successfuly add users to my database. So, it runs through the try block but also the catch ... so thats a big confusing. The only response I am getting on postman is the server error 500 message from the catch block.
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const { check, validationResult } = require('express-validator');
const User = require('../../models/User');
// #route GET api/users
// #desc Test route
// #access Public
router.post(
'/',
[
check('name', 'Name is required').not().isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
'Please enter a password with 6 or more characters'
).isLength({ min: 6 }),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, email, password } = req.body;
try {
let user = await User.findOne({ email });
// see if user exists
if (user) {
return res.status(400).json({
errors: [{ msg: 'User already exists' }],
});
}
// get users gravatar
const avatar = gravatar.url(email, {
s: '200',
r: 'pg',
d: 'mm',
});
user = new User({
name,
email,
avatar,
password,
});
// encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// return jsonwebtoken
return res.send('User registered');
} catch (error) {
console.log(error.message);
res.status(500).send('Server error');
}
}
);
module.exports = router;
The User schema
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatar: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model('user', UserSchema);
module.exports = User;
connection configuration:
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () => {
try {
await mongoose.connect(db, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log('Connected to MongoDB');
} catch (err) {
console.error(err.message);
process.exit(1);
}
};
module.exports = connectDB;

I am getting this error : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

When I am sending POST Request for Login, then show this Error. I have used mongoose & MongoDB Atlas.
If I send POST request with valid email & password, it also shows this error.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent
to the client
But POST request for registration is working well.
User Model
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true
},
balance: Number,
income: Number,
expense: Number,
transactions: {
type: [{
type: Schema.Types.ObjectId,
ref: 'Transaction'
}]
}
})
const User = mongoose.model('User', userSchema)
module.exports = User
User Controller
const registorValidate = require('../validator/registrationValidate')
const User = require('../models/userModel')
const bcrypt = require('bcrypt')
const loginValidate = require('../validator/loginValidator')
const jwt = require('jsonwebtoken')
module.exports = {
login: (req, res) => {
const { email, password } = req.body
let logValidate = loginValidate({ email, password })
if (!logValidate.isValid) {
res.status(400).json(logValidate.error)
return
}
User.findOne({ email })
.then(user => {
if (!user) {
console.log(`${email} not found`)
res.json({
msg: `${email} not found`
})
}
bcrypt.compare(password, user.password, (err, result) => {
if (err) {
res.status(400).json({
msg: 'Error occured'
})
}
if (!result) {
res.status(404).json({
msg: `Password doesn't match`
})
}
let token = jwt.sign({
_id: user._id,
name: user.name,
email: user.email
}, 'SECRET', { expiresIn: '2h' })
res.status(200).json({
msg: 'Login successful',
token: `Bearer ${token}`
})
})
return
})
.catch(err => {
res.status(500).json({
msg: 'Error occured'
})
})
res.end()
},
registration: (req, res) => {
let { name, email, password, confirmPassword } = req.body
let validate = registorValidate({ name, email, password, confirmPassword })
if (!validate.isValid) {
res.status(400).json(validate.error)
} else {
User.findOne({ email })
.then(user => {
if (user) {
res.json({
msg: `${email} is already exist`
})
} else {
bcrypt.hash(password, 11, (err, hash) => {
if (err) {
res.status(500).json({
msg: 'Server error occured'
})
}
let user = new User({
name,
email,
password: hash
})
user.save()
.then(user => {
res.status(201).json({
msg: `Thanks ${name} for your registration`,
user
})
})
.catch(err => {
res.status(500).json({
msg: 'Error occured'
})
})
})
}
})
.catch(err => {
res.status(500).json({
msg: 'Error occured'
})
})
}
}
}
Login Validator
const validator = require('validator')
const validate = user => {
let error = {}
// Email validator
if (!user.email) {
error.email = 'Please provide an Email'
} else if (!validator.isEmail(user.email)) {
error.email = 'Please provide a valid Email'
}
// Password validate
if (!user.password) {
error.password = 'Please provide a password'
} else if (user.password.length < 6) {
error.password = 'Password Must be greater or Equal to 6 characters'
}
return {
error,
isValid: Object.keys(error).length === 0
}
}
module.exports = validate
Thanks.
You don't need to put res.end() because when you called res.json() earlier, it already sent the response.
Please be advised that you should return when you call res.end(), res.send(), 'res.json()' and other operations that send the response, just like what you did with res.status(400).json(logValidate.error)
This should be one of the ways prevent you from getting ERR_HTTP_HEADERS_SENT, but keep in mind that if you have nested callbacks, you should return from the outer scope as well