Basically, I get an error saying "Cannot set headers after they are sent to the client". i tried redoing everything.
this is the form code:
const loader = document.querySelector('.loader');
// selecionar inputs
const submitBtn = document.querySelector('.submit-btn');
const name = document.querySelector('#name');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const number = document.querySelector('#number');
const tac = document.querySelector('#terms-and-cond');
const notification = document.querySelector('#notifications');
submitBtn.addEventListener('click', () => {
if(name.value.length < 3){
showAlert('name must be 3 letters long');
} else if (!email.value.length){
showAlert('enter your email');
} else if (password.value.length < 8){
showAlert('password should be 8 letters long');
} else if (!number.value.length){
showAlert('enter your phone number');
} else if (!Number(number.value) || number.value.length < 10){
showAlert('invalid number, please enter valid one');
} else if (!tac.checked){
showAlert('You must agree to our terms and conditions');
} else{
// para dar submit
loader.style.display = 'block';
sendData('signup', {
name: name.value,
email: email.value,
password: password.value,
number: number.value,
tac: tac.checked,
notification: notification.checked,
seller: false
})
}
})
// mandar a função dos dados
const sendData = (path, data) => {
fetch(path, {
method: 'post',
headers: new Headers({'Content-Type': 'application/json'}),
body: JSON.stringify(data)
}).then((res) => res.json())
.then(response => {
processData(response);
})
}
const processData = (data) => {
loader.style.display = null;
if(data.alert){
showAlert(data.alert);
}
}
const showAlert = (msg) => {
let alertBox = document.querySelector('.alert-box');
let alertMsg = document.querySelector('.alert-msg');
alertMsg.innerHTML = msg;
alertBox.classList.add('show');
setTimeout(() => {
alertBox.classList.remove('show');
}, 3000);
}
again, and I still get the same error...
and this is the server code:
// importar os packages
const express = require('express')
const admin = require('firebase-admin');
const bcrypt = require('bcrypt');
const path = require('path');
// setup da firebase - admin
let serviceAccount = require("./haza---pap-firebase-adminsdk-lrx0l-0da425a226.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let db = admin.firestore();
// declarar um caminho estatico
let staticPath = path.join(__dirname, "public");
// inicializar o express.js
const app = express();
//middlewares
app.use(express.static(staticPath));
app.use(express.json());
// routes
// home route
app.get("/", (req, res) => {
res.sendFile(path.join(staticPath, "index.html"));
})
//route do signup
app.get('/signup', (req, res) =>{
res.sendFile(path.join(staticPath, "signup.html"));
})
app.post('/signup', (req, res) => {
let {name, email, password, number, tac, notification } = req.body;
// validações do form
if (name.length < 3){
return res.json({'alert': 'name must be 3 letters long'});
} else if (!email.length){
return res.json({'alert': 'enter your email'});
} else if (password.length < 8){
return res.json({'alert' :'password should be 8 letters long'});
} else if (!number.length){
return res.json({'alert' : 'enter your phone number'});
} else if (!Number(number) || number.length < 10){
return res.json({'alert' :'invalid number, please enter valid one'});
} else if (!tac){
return res.json({'alert' : 'You must agree to our terms and conditions'});
} else {
// guardar utilizadores na base de dados
db.collection('users').doc(email).get()
.then(user => {
if(user.exists){
return res.json({'alert': 'email already exists'});
} else{
// encriptar a password antes de guarda-la.
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
req.body.password = hash;
db.collection('users').doc(email).set(req.body)
.then(data => {
res.json({
name: req.body.name,
email: req.body.email,
seller: req.body.seller,
})
})
})
})
}
})
}
res.json('data recieved');
})
//route do 404
app.get('/404', (req, res) => {
res.sendFile(path.join(staticPath, "404.html"));
})
app.use((req, res) => {
res.redirect('/404');
})
app.listen(3000, () => {
console.log('listening on port 3000.......');
})
CodePudding user response:
You are setting some data in response obj after send is being processed by node js. Try using: res.end() after your all res.send.. events
CodePudding user response:
You are sending response twice in /signup
route.
Remove res.json('data recieved');
and it should work fine
CodePudding user response:
That Error happens when you res. and then res. again to the client. Responding to the client several times is erroneous in node.
Check your route req,res cycles. Remember middleware .use() execute sequentially, and routes execute usually in between so...good luck