Home > Blockchain >  node.js : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
node.js : Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Time:10-04

I am trying to write the official website login function, the membership function has been completed, but the backend will receive an error. After I try to log in successfully, the original I loaded the home page a few times, this error will be several times (click the official website icon to reorganize several times, the same error will jump out several times)

This website backend uses express.js to create an account with Google's firebase feature. This error does not cause my web account to create a logout function. I just don't know why I repeatedly jump out of the wrong way to see it so uncomfortable. I have been search about the error message but none of them have been successfully resolved.

So let's see if i can ask the big guys on the Internet.

Repeated errors:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:794:10)
    at ServerResponse.contentType (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:624:15)
    at ServerResponse.send (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:149:14)
    at done (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:1035:10)
    at tryHandleCache (/Users/leziyang/Code/ttumc/node_modules/ejs/lib/ejs.js:280:5)
    at View.exports.renderFile [as engine] (/Users/leziyang/Code/ttumc/node_modules/ejs/lib/ejs.js:491:10)
    at View.render (/Users/leziyang/Code/ttumc/node_modules/express/lib/view.js:135:8)
    at tryRender (/Users/leziyang/Code/ttumc/node_modules/express/lib/application.js:657:10)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:372:5)
    at ServerResponse.setHeader (node:_http_outgoing:576:11)
    at ServerResponse.header (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:794:10)
    at ServerResponse.contentType (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:624:15)
    at ServerResponse.send (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:149:14)
    at done (/Users/leziyang/Code/ttumc/node_modules/express/lib/response.js:1035:10)
    at tryHandleCache (/Users/leziyang/Code/ttumc/node_modules/ejs/lib/ejs.js:280:5)
    at View.exports.renderFile [as engine] (/Users/leziyang/Code/ttumc/node_modules/ejs/lib/ejs.js:491:10)
    at View.render (/Users/leziyang/Code/ttumc/node_modules/express/lib/view.js:135:8)
    at tryRender (/Users/leziyang/Code/ttumc/node_modules/express/lib/application.js:657:10)

and this is my javascript code:

const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require("lodash");


const app = express();
const { response } = require("express");

app.use(express.json());
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

const { initializeApp } = require("firebase/app");
const {
    getAuth, onAuthStateChanged, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut
} = require("firebase/auth");

const {
    getFirestore, doc, setDoc, addDoc, collection
} = require("firebase/firestore");

const credentials = require(__dirname   "/serviceAccountKey.json");
const initApp = initializeApp(credentials);

const auth = getAuth(initApp);
const db = getFirestore(initApp);

let signStatus = 0;





app.get("/", function (req, res) {
    onAuthStateChanged(auth, (user) => {
        signStatus = 0;
        if (user) {
            signStatus = 1;
        } else {
            signStatus = 0;
        }
        return res.render("index", { signStatus: signStatus })
    });
})


app.get("/login", function (req, res) {
    return res.render("login", { signStatus: signStatus })
})

app.post("/login",  function (req, res) {
    const email = req.body.email;
    const password = req.body.password;
    signInWithEmailAndPassword(auth, email, password)
        .then( (userCredential) => {
            signStatus = 1;
            return  res.redirect("/");
        })
        .catch( (error) => {            
            return  res.send("<h1>登入失敗囉低能兒!</h1><br>" )
        });

})

app.get("/signup", function (req, res) {
    return res.render("signup", { signStatus: signStatus })
})

app.post('/signup',  (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    const userName = req.body.userName;
    const schoolNumber = req.body.schoolNumber;
    const id = req.body.email;
    const userJson = {
        email: email,
        userName: userName,
        schoolNumber: schoolNumber,
        adminPower: false,
    };
    createUserWithEmailAndPassword(auth, email, password)
        .then( (userCredential) => {

             setDoc(doc(db, "users", id), userJson);
            return  res.redirect("/");
        })
        .catch( (error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorCode, errorMessage);
            return  res.send("<h1>創建失敗囉低能兒!</h1><br>"   errorMessage)
        });




})

app.get('/signout',  function (req, res) {
    signOut(auth).then( () => {

        signStatus = 0;
        return  res.redirect("/");
    }).catch( (error) => {
        return  res.send("<h1>好像出了點問題 QAQ</h1>")
    });

})



app.listen(3000, function () {
    console.log("Server started on port 3000");
});

i am so poor in English.very sorry about this

CodePudding user response:

Here /login has successful response its redirect to /. Here also return one response.

You can use function instead of API request to find user.

Post : /login

app.post("/login",  function (req, res) {
    const email = req.body.email;
    const password = req.body.password;
    signInWithEmailAndPassword(auth, email, password)
        .then( (userCredential) => {
            signStatus = 1;
            return  res.redirect("/");   // here 1st response
        })
        .catch( (error) => {            
            return  res.send("<h1>登入失敗囉低能兒!</h1><br>" )
        });

})

Get : "/"

    app.get("/", function (req, res) {
    onAuthStateChanged(auth, (user) => {
        signStatus = 0;
        if (user) {
            signStatus = 1;
        } else {
            signStatus = 0;
        }
        return res.render("index", { signStatus: signStatus })   // 2nd response...
    });
})

try below method

app.post("/login",  function (req, res) {
      const email = req.body.email;
      const password = req.body.password;
      signInWithEmailAndPassword(auth, email, password)
          .then( (userCredential) => {
              onAuthStateChanged(auth, (user) => {
                signStatus = 0;
                if (user) {
                    signStatus = 1;
                } else {
                    signStatus = 0;
                }
                return res.render("index", { signStatus: signStatus })
            });
          })
          .catch( (error) => {            
              return  res.send("<h1>登入失敗囉低能兒!</h1><br>" )
          });
    })
  • Related