Realtime database using Firebase - javascript

So I'm setting up a login and register page with the firebase authentication and realtime database. However, the authentication works but my data doesn't get pushed into my database. My alert messages are also not popping up and i can't figure it out.
HTML
<form action="../index.html">
<div class="input">
<input type="text" placeholder="Naam" id="name" required>
</div>
<div class="input">
<input type="email" placeholder="E-mail" name="email" id="email" required>
</div>
<div class="right-inner-addon">
<i class="fa-solid fa-eye-slash" id="togglePassword"></i>
<div class="input">
<input type="password" placeholder="Password" name="psw" id="psw" required>
</div>
</div>
<button type="submit" id="submitData" class="registerbtn">Meld je aan</button>
</form>
Javascript
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-auth.js";
import { getDatabase,set,ref } from "https://www.gstatic.com/firebasejs/9.8.3/firebase-database.js";
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
submitData.addEventListener('click',(e) =>{
let email = document.getElementById('email').value;
let password = document.getElementById('psw').value;
let name = document.getElementById('name').value
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
set(ref(database, 'users/' + user.uid), {
name: name,
email: email,
password : password
})
.then(() => {
// Data saved successfully!
alert ('Gebruiker succesvol geregistreerd');
})
.catch((error) => {
// The write failed...
alert(error);
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
})
I'm hiding my configuration ofcourse.

Related

File input always shows No file chosen

I'm building a form using React & Nodejs & MongoDB, where you can fill the form and upload a file with some other text inputs.
However, after i submit, i receive only text inputs in my database. The chosen file (desired to upload) doesn't appear at all in the database. I am expecting to get all the data form (the uploaded file and text inputed) in my database.
I tested my backend and it works correctly (it uploads all the inputs).
Ps: In browser, when i select a file (.pdf) to upload, the file input always shows no file chosen !
Console.dev : Error
{title: 'Miss', fname: 'zaezae', lname: 'zaeazee', email: 'zaea#mail.com', phoneNumber: '12345678', …}
coverLetter: "zaez e az ezae e zae aeae "
cv: ""
email: "zaea#mail.com"
fname: "zaezae"
lname: "zaeazee"
myFile: "C:\\fakepath\\test.pdf"
phoneNumber: "12345678"
title: "Miss"
Formulaire.jsx:29
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')
at submit (Formulaire.jsx:29:1)
Backend:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
Axios.js:
import axios from 'axios'
export const Axios = axios.create({
baseURL: 'http://localhost:5000',
})
Apiroutes.js:
const form = "/api/form"
export const requests = {
formApi: {
store: form + '/store'
}
}
formservices.js:
import { Axios } from "../config/axios";
import { requests } from "../config/apiroutes";
export const FormService = {
store: (data) => {
Axios.post(requests.formApi.store, data)
.then(res => {
return res
})
.catch(err => {
return err
})
}
}
formController.js :
const form = require('../models/FormModel')
const store = (req, res, next) => {
let candidate = new form({
title: req.body.title,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
phoneNumber: req.body.phoneNumber,
coverLetter: req.body.coverLetter
})
if (req.file) {
candidate.cv = req.file.path
}
candidate.save()
.then(response => {
res.json({
success: true,
message: 'Candidate added successfully!',
data: candidate,
})
})
.catch(error => {
res.json({
success: false,
message: 'An error occured!',
error: error,
})
})
}
module.exports = {
store
}
Frontend:
Formulaire.jsx :
import React, { useState } from 'react'
import Divider from '#mui/material/Divider';
import './Formulaire.css'
import { titles } from '../../mock/titles'
import { FormService } from '../../services/formServices';
const Form = () => {
const [storedata, setstoredata] = useState({
title: '',
fname: '',
lname: '',
email: '',
phoneNumber: '',
cv: '',
coverLetter: ''
})
const handleChange = e => {
const { name, value } = e.target;
setstoredata(prevState => ({
...prevState,
[name]: value
}));
};
const submit = async () => {
console.log(storedata);
await FormService.store(storedata)
.then(res => {
console.log(res);
})
.catch(err => {
return err
})
}
return (
<div className='container'>
<div className='header'>
<div className='title'>
<a className='quizbutton' href="/quiz">Take a Test (Quiz)</a>
<h1>Apply for a Position :</h1>
</div>
</div>
<Divider style={{ maxWidth: '1000px', marginLeft: '250px' }} />
<div id="content">
<div id="formWrapper">
<form id="msform" method='post' action='/uploadFile' enctype="multipart/form-data">
<fieldset id="fieldset3">
<h2 class="fs-title">Please complete the form below for a position with us.</h2>
<h3 class="fs-subtitle">Reference 0001</h3>
{/* <div class="fs-error"></div> */}
<div class="wrapper">
<label for="title">Title :</label>
<select name="title" value={storedata.title} onChange={handleChange}>
<option hidden></option>
{
titles.map((c, i) => {
return (
<option key={i} value={c}>{c}</option>
)
})
}
</select>
<label for="fname">First Name<span>*</span> :</label>
<input type="text" name="fname" value={storedata.fname} onChange={handleChange} id="fname" placeholder="Please enter your first name" required />
<label for="lname">Last Name<span>*</span> :</label>
<input type="text" name="lname" value={storedata.lname} onChange={handleChange} id="lname" placeholder="Please enter your last name" required />
<label for="email">Email<span>*</span> :</label>
<input type="email" name="email" value={storedata.email} onChange={handleChange} id="email" placeholder="Please enter your email" required />
<label for="phoneNumber">Phone N° :</label>
<input type="number" name="phoneNumber" value={storedata.phoneNumber} onChange={handleChange} id="phoneNumber" placeholder="Phone number" />
<label for="CV">Upload CV <span>*</span>:</label>
<input type="file" name="myFile" id="cv" value={storedata.cv} onChange={handleChange} accept="application/msword, application/pdf" placeholder="Cover Letter" required />
<label for="coverLetter">Cover Letter :</label>
<textarea type="text" name="coverLetter" value={storedata.coverLetter} onChange={handleChange} id="coverLetter" placeholder="cover Letter" />
</div>
<br />
<input type="submit" name="submit" class="submit action-button" value="Submit" onClick={submit} />
</fieldset>
</form>
</div>
</div>
</div>
)
}
export default Form
I fixed my problem by changing name="myFile" id="cv" to name="cv" id="cv"

How can I solve this Fetch problem in React.js?

I have this fetch where I'm trying to post a form in MongoDB.
When I fill the form I get this back:
SyntaxError: Unexpected end of input at ContactRequest.js:3:1
And I don't know why, because the fetch receives the data from the form and testing the endpoint in postman it works perfectly.
The fetch should works because I used the same Fetch in other projects.
This is the fetch component.
const contactRequest = (params) => {
console.log(`Test ${JSON.stringify(params)}`);
fetch(`http://localhost:4000/contact`, {
method: "POST",
body: JSON.stringify(params),
mode: "no-cors",
headers: {
'Content-Type': 'application/json'
}})
.then(res => res.json())
.catch((e) => console.error(e));
};
export default contactRequest;
This is the form component:
import React, {useState} from 'react';
import contactRequest from '../Request/ContactRequest';
import './Contact.css';
const initialState = {
nameAndSurname: "",
email: "",
phoneNumber: "",
message: "",
};
const Contact = () => {
const [contactData, setContactData] = useState(initialState);
const handlerInput = (e) => {
setContactData({
...contactData,
[e.target.name] : e.target.value
});
};
const handlerSubmit = (e) => {
e.preventDefault();
setContactData(initialState);
contactRequest(contactData);
alert("Hemos recibido tu mensaje.");
}
return (
<div>
<form onSubmit={handlerSubmit}>
<label className="nameAndSurname-label">
Nombre y Apellido: <br/>
<input
id="nameAndSurname"
type="text"
name="nameAndSurname"
placeholder="Ingrese su nombre y apellido"
onChange={handlerInput}
value={contactData.nameAndSurname}
required/> <br/>
</label>
<div className="email-phoneNumber-div">
<label>
Email: <br/>
<input
id="email"
type="email"
name="email"
placeholder="Ingrese su email"
onChange={handlerInput}
value={contactData.email}
required/> <br/>
</label>
<label>
Numero de teléfono: <br/>
<input
id="phoneNumber"
type="number"
name="phoneNumber"
placeholder="Ingrese su numero de teléfono"
onChange={handlerInput}
value={contactData.phoneNumber}
required/> <br/>
</label>
</div>
<label>
Mensaje: <br/>
<input
id="message"
type="text"
name="message"
placeholder="Ingrese su mensaje"
onChange={handlerInput}
value={contactData.message}
required/> <br/>
</label>
<label>
Al enviar este formulario, acepto los terminos y condiciones.
</label>
<button
id="submit-btn"
type="submit"
value="Submit">Enviar</button>
</form>
</div>
</div>
)
}
export default Contact;
This is the Endpoint.
const express = require('express');
const router = express.Router();
const Contact = require('../models/Contact.js');
router.post('/contact', (req, res) => {
console.log(req.body);
console.log(req.text);
let contact = new Contact()
contact.nameAndSurname = req.body.nameAndSurname
contact.email = req.body.email
contact.phoneNumber = req.body.phoneNumber
contact.message = req.body.message
contact.save((err, contactStored) => {
if(err) {
res.status(500).send({message: `Error ${err}`})
}else {
res.status(200).send({contact: contactStored})
}
})
})
module.exports = router;
Why are you using mode: "no-cors"? This results in an "opaque" response, without body, so without anything to convert to json

VueJs3 sending data from one component to another

I am currently working on a VueJs3 Project. I already coded a login system, which works perfectly fine. I now want to have a div on the homepage, that tells the user with which account they are logged in.
"You are logged in as:" + username
I therefore, have to send the username from the login component to the home component. Can someone help me out here? I have tried out a lot of ways but none of them seem to work.
Btw. the components are all saved in the components folder
Here is my code:
home.vue
<div class="home">
<h1>You are logged in as: {{currentusername}}</h1>
<Maschinen/>
</div>
</template>
<script>
import Maschinen from '#/components/Maschinen.vue'
import axios from 'axios'
export default {
name: 'Home',
components: {
Maschinen
},
data() {
return {
currentusername: null,
}
},
async created() {
const response = await axios.get('http://localhost:8080/user/hetwinuser', {
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
});
this.currentusername= (response.data.username);
}
}
</script>
login.vue:
<template>
<form #submit.prevent="handleSubmit">
<h1>Login</h1>
<!--username + pw input for login-->
<div class="form-group">
<label id="username">Username:</label>
<input id="usernameinput" type="text" class="form-control" v-model="username" placeholder="Username">
</div>
<div>
<label id="password">Password:</label>
<input id="passwordinput" type="password" class="form-control" v-model="password" placeholder="Password">
</div>
<!--enter buttons-->
<button class="enter">Enter</button>
<router-link to="/register" id="goToRegister" tag="button">Register</router-link>
</form>
</template>
<script>
import axios from 'axios';
export default {
name: "Login",
data: () => {
return {
username: '',
password: ''
}
},
methods: {
async handleSubmit() {//executed when enter button is pressed
const data = {
username: this.username,
password: this.password
};
axios.post('http://localhost:8080/authenticate', data) //post the username + pw and will receive the token in exchange
.then(
res => {
localStorage.setItem('token', res.data.jwt);
localStorage.setItem('currentusername', this.username);
//console.log(localStorage.getItem('token'));
}
).catch(
err => {
console.log(err)
}
);
}
},
}
</script>```
username and password
Define it under store -> state.js. Then where you want it
Use it as "this.$store.state.username"

How to use Axios from backend to frontend

I'm using reactjs as my development tool and mongoDB as my backend database.
I have my backend react code as following:
const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const { User, VerificationCode } = require("../models");
const { isLoggedIn, getLoggedInUserId, generateRefreshToken } = require("./middlewares");
const sendVerificationEMail = require("./bin/send_email").sendVerificationEmail;
require("dotenv").config();
const router = express.Router();
router.post("/register", async (req, res, next) => {
const { email, username, password, first_name, last_name } = req.body;
try {
// Check if the email is duplicating
let existingUser = await User.findOne({ where: { email } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "User already exists.",
});
}
existingUser = await User.findOne({ where: { username } });
if (existingUser) {
return res.status(409).json({
success: false,
message: "Same nickname user exists.",
});
}
const hash = await bcrypt.hash(password, 12);
await User.create({
email,
username,
password: hash,
first_name,
last_name,
});
return res.status(200).json({
success: true,
message: "Signup successful.",
});
} catch (error) {
return res.json({
success: false,
message: "Signup failed.",
});
}
});
// Login
// Create token and return to user (httpOnly cookies)
router.post("/login", async (req, res, next) => {
const { email, password } = req.body;
// Make a inquiry of the user through email
try {
const user = await User.findOne({ where: { email }, raw: true });
if (!user) {
return res.status(401).json({
success: false,
message: "No member exists.",
});
}
// Check password
const isMatch = await bcrypt.compare(password, user.password);
if (isMatch) {
// If the password matches,create JWT payload
const payload = {
uid: user.id,
};
// JWT token create
const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: req.app.get("jwt_expiration") });
// New refresh token and create expiration for it
let refresh_token = generateRefreshToken(req, user.id);
let refresh_token_maxage = new Date() + req.app.get("jwt_refresh_expiration");
// Browswer httpOnly cookie setting
res.cookie("access_token", token, {
// secure: true,
httpOnly: true,
});
res.cookie("refresh_token", refresh_token, {
// secure: true,
httpOnly: true,
});
// Save the account id as key and save in Redis server
req.client.set(
user.id,
JSON.stringify({
refresh_token: refresh_token,
expires: refresh_token_maxage,
}),
req.client.print
);
return res.json({
success: true,
uid: user.id,
message: "Login Successful",
});
} else {
return res.status(401).json({
success: false,
message: "Password's don't match.",
});
}
} catch (error) {
console.error(error);
res.status(401).json({
success: false,
message: "Login Error",
});
}
});
module.exports = router;
And I have my Login frontend code as following: (Login.js)
import React, { Component } from "react";
import login from "../picture/login.png";
import Form from "react-bootstrap/Form";
import axios from "axios";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Login</h2>
<hr />
<div class="row h-100 justify-content-center align-items-center">
<img src = {login}
width = '550'
height = '200'
alt='Login2'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
<Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Remember me" />
</Form.Group>
<button type="submit" className="btn btn-info btn-block">Submit</button>
<div className = "App-wrapper">
<p className="forgot-password text-right">
<a href="signup"to="/signup">
Sign Up | </a>
<a href="password"to="/pasword">
Find Password</a>
</p>
</div>
</form>
</div>
</div>
</div>
);
}
}
My Signup frontend code is:(Signup.js)
import React, { Component } from "react";
import Form from "react-bootstrap/Form";
import welcome from "../picture/welcome.png";
export default class SignUp extends Component {
render() {
return (
<div style = {{
backgroundColor:'#f7feff'
}}>
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<form class="col-6">
<br/><br/><br/>
<h2>Sign Up</h2>
<hr />
<div class = "row h-100 justify-content-center align-items-center">
<img src = {welcome}
width = '550'
height = '200'
alt='signup'/>
</div>
<Form.Group controlId="formBasicEmail">
<Form.Label>*Email address</Form.Label>
<Form.Control type="email" placeholder="Enter email" />
</Form.Group>
<Form.Group controlId="formBasicUsername">
<Form.Label>*Username</Form.Label>
<Form.Control placeholder="Enter username" />
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>*Password</Form.Label>
<Form.Control type="password" placeholder="Enter password" />
</Form.Group>
<Form.Group controlId="formBasicFirstname">
<Form.Label>*Firstname</Form.Label>
<Form.Control placeholder="Enter firstname" />
</Form.Group>
<Form.Group controlId="formBasicLastname">
<Form.Label>*Lastname</Form.Label>
<Form.Control type placeholder="Enter lastname" />
</Form.Group>
<Form.Group controlId="formBasicTelephone">
<Form.Label>Telephone</Form.Label>
<Form.Control type="number"placeholder="Enter telephone number"/>
</Form.Group>
<Form.Text className="text-muted">
Fields that are marked with asterisk(*) are compulsory.
</Form.Text>
<button type="submit" className="btn btn-info btn-block">Sign Up</button>
<p className="forgot-password text-right">
Already registered? sign in?
</p>
</form>
</div>
</div>
</div>
);
}
}
I really don't know how to connect backend and frontend using axios. The login server url is localhost:8002/auth/login and for signup: localhost:8002/auth/signup
In your React component, you have to make a function that uses axios to call the backend, and then add that as a onClick handler to the submit button.
To make a request with axios you have to use the functions available on the axios module. In your case, this could look something like this:
function onSubmit() {
axios.post('localhost:8002/auth/login',
{username: username,
password: password });
}
Be aware that axios.post returns a promise, so you would have to await it/use .then to get the response from the backend. When you have the function, you can attach it to your login button like this:
<button type="submit" className="btn btn-info btn-block" onClick={onSubmit}>Submit</button>
EDIT: And the username and password values are of course the values that the user has entered via the input fields. You can store these in the state of the component.

Save form data in modal class that contains an array [Angular]

How can I save form data that contains an array.so I faced an issue which is the adresses is null whereas other data like city region aren't null. someone here have an idea ?!
Iuser.interface
export interface UserData {
id: string;
email: string;
adresses: string[];
}
Component.ts
onSubmit() {
const {adresse1, ...rest} = this.form;
const userData: UserData = {...rest, adresses: [adresse1]};
this.userservice.updateProfile(userData, this.currentUser.id).subscribe(
data => {
console.log(data);
this.isSuccessful = true;
},
err => {
this.errorMessage = err.error.message;
}
);
}
component.html
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" placeholder=""
name="adresse"
[(ngModel)]="form.adresse"
required
#adresse="ngModel">
</div> <!-- form-group end.// -->
<div class="form-row">
<div class="form-group col-md-6">
<label>Region</label>
<input type="text" class="form-control"
name="region"
[(ngModel)]="form.region"
required
#region="ngModel">
</div> <!-- form-group end.// -->
You are reading adresse1 from this.form inside onSubmit() method which is not a part of your form object,your address is actually stored inadresse property.Please update your code within submit block as
const {adresse, ...rest} = this.form;
const userData: UserData = {...rest, adresses: [adresse]};

Categories