发送到客户端后无法设置 headers(express-session 数据到 ejs html)

Cannot set headers after they are sent to the client (express-session data to ejs html)

我遇到以下问题:每次我访问用户个人资料页面(见下文)时,我都会在控制台中收到此错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at new NodeError (node:internal/errors:329:5)
    at ServerResponse.setHeader (node:_http_outgoing:573:11)
    at ServerResponse.header (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\response.js:170:12)
    at C:\Users\Lyrdum\Desktop\Projects\app\app.js:36:9
    at Layer.handle_error (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\router\layer.js:71:5)
    at trim_prefix (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\router\index.js:315:13)
    at C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Lyrdum\Desktop\Projects\app\node_modules\express\lib\router\index.js:275:10)

我认为问题出在 ejs 语法上,因为我从 express-session 获取数据并使用 ejs 语法在 html 文件中打印(例如:<%= user.name %>, <%= user.email %>), 我不知道还能做什么,如果有人有更好的主意或者一些 tips/tricks 会有用,无论如何谢谢!

快递路线:

const express = require("express");
const User = require("./user");
const router = express.Router();
 
const user = new User();
 
var online = "undefined";
 
// Get
router.get("/login", (req, res, next) => {
  if (req.session.user) {
    online = req.session.user.username;
    res.redirect("/profile");
  }
  res.render("login", { user: req.session.user });
});
 
router.get("/register", (req, res, next) => {
  if (req.session.user) {
    res.redirect("/profile");
  }
  res.render("register", { user: req.session.user, online });
});
 
// Get
router.get("/", (req, res, next) => {
  // If there is a session named user that means the use is logged in. so we redirect him to home page by using /home route below
  if (req.session.user) {
    online = req.session.user.username;
    res.redirect("/profile");
    return;
  }
  // IF not we just send the index page.
  res.render("index", { user: req.session.user, online });
});
 
router.get("/error", (req, res, next) => {
  if (req.session.user) {
    res.render("error", { user: req.session.user, online });
  }
  res.render("error", { user: req.session.user, online });
});
 
router.get("/profile", (req, res, next) => {
  if (req.session.user) {
    online = req.session.user.username;
    res.render("userprofile", { user: req.session.user, online });
    return res.status(400).json({
      status: "error",
      error: "req body cannot be empty",
    });
  }
  res.redirect("/index");
  return res.status(400).json({
    status: "error",
    error: "req body cannot be empty",
  });
});
 
router.get("/logout", (req, res, next) => {
  // Check if the session is exist
  if (req.session.user) {
    // destroy the session and redirect the user to the index page.
    req.session.destroy(function () {
      res.redirect("/");
    });
  }
});
 
//Post
router.post("/login", (req, res, next) => {
  // The data sent from the user are stored in the req.body object.
  // call our login function and it will return the result(the user data).
  user.login(req.body.username, req.body.password, function (result) {
    if (result) {
      // Store the user data in a session.
      req.session.user = result;
      req.session.opp = 1;
      online = req.session.user.username;
      // redirect the user to the home page.
      res.redirect("/profile");
    } else {
      // if the login function returns null send this error message back to the user.
      res.send("Username/Password incorrect!");
    }
  });
});
 
router.post("/register", (req, res, next) => {
 
  let userInput = {
    username: req.body.username,
    password: req.body.password,
    email: req.body.email,
  };
 
  user.register(userInput, function (lastId) {
    // if the creation of the user goes well we should get an integer (id of the inserted user)
    if (lastId) {
      // Get the user data by it's id. and store it in a session.
      user.find(lastId, function (result) {
        req.session.user = result;
        req.session.opp = 0;
        online = req.session.user;
        res.redirect("/profile");
      });
    } else {
      console.log("Error creating a new user ...");
    }
  });
});
 
module.exports = router;

用户reg/login逻辑:

const pool = require("./mysql");
const bcrypt = require("bcrypt");


function User() {}

User.prototype = {

    find: function(user = null, callback) {

        if (user) {
            var field = Number.isInteger(user) ? "id" : "username";
        }
        let sql = `SELECT * FROM users WHERE ${field} = ?`;

        pool.query(sql, user, function(error, result) {
            if (error) throw error;

            if (result.length) {
                callback(result[0]);
            } else {
                callback(null);
            }
        });
    },
    
    login: function(username, password, callback) {
        this.find(username, function(user){
            if (user) {

                if (bcrypt.compareSync(password, user.password)) {
                    callback(user);
                    return;
                }
            }
            callback(null);
        });
    },

    register: function(body, callback) {
        
        var username = body.username;
        var email = body.email;
        var password = bcrypt.hashSync(body.password,10);

        let sql = `INSERT INTO users(username, password, email) VALUES ('${username}', '${password}', '${email}')`;

        pool.query(sql, function(error, result){
            if (error) throw error;
            callback(result.insertId);
        });
    },
}

module.exports = User;

用户配置文件(每次我访问这个,我都会在控制台中收到错误)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= online %> | Profile</title>
    <link href="css/userprofile.css" rel="stylesheet" type="text/css">
    <%- include('index.ejs') -%>
</head>

<body>
    <div class="container">
        <div class="main-body">

            <!-- Breadcrumb -->
            <nav aria-label="breadcrumb" class="main-breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item active" aria-current="page">Welcome to <%= user.username %> profile!</li>
                </ol>
            </nav>
            <!-- /Breadcrumb -->

            <div class="row gutters-sm">
                <div class="col-md-4 mb-3">
                    <div class="card">
                        <div class="card-body">
                            <div class="d-flex flex-column align-items-center text-center">
                                <img src='img/<%= user.avatar %>.png' class="rounded-circle" style="height:auto;" width="150" height="250">
                                <div class="mt-3">
                                    <h5>
                                        <b> <%= user.username %></b>
                                    </h5>
                                    <p class="text-secondary mb-1"> <img src='img/ig.png' class="rounded-circle" style="height:auto;" width="24" height="24">   <%= user.rank %></p>
                                    <button class="btn btn-outline-primary">Editeaza</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card mt-3">
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                <h6 class="mb-0"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="feather feather-globe mr-2 icon-inline">
                                        <circle cx="12" cy="12" r="10"></circle>
                                        <line x1="2" y1="12" x2="22" y2="12"></line>
                                        <path
                                            d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z">
                                        </path>
                                    </svg>Personal Website</h6>
                                <span class="text-secondary"><%= user.nick %></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                <h6 class="mb-0"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="feather feather-github mr-2 icon-inline">
                                        <path
                                            d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22">
                                        </path>
                                    </svg>Github</h6>
                                <span class="text-secondary"><%= user.github %></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                <h6 class="mb-0"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="feather feather-twitter mr-2 icon-inline text-info">
                                        <path
                                            d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z">
                                        </path>
                                    </svg>Twitter</h6>
                                <span class="text-secondary"><%= user.twitter %></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                <h6 class="mb-0"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="feather feather-instagram mr-2 icon-inline text-danger">
                                        <rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
                                        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
                                        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
                                    </svg>Instagram</h6>
                                <span class="text-secondary"><%= user.instagram %></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                <h6 class="mb-0"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                        stroke-linecap="round" stroke-linejoin="round"
                                        class="feather feather-facebook mr-2 icon-inline text-primary">
                                        <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z">
                                        </path>
                                    </svg>Facebook</h6>
                                <span class="text-secondary"><%= user.facebook %></span>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-sm-3">
                                    <h6 class="mb-0">Nume Complet</h6>
                                </div>
                                <div class="col-sm-9 text-secondary">
                                    <%= user.nick %>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-3">
                                    <h6 class="mb-0">Nivel</h6>
                                </div>
                                <div class="col-sm-9 text-secondary">
                                    <%= user.rank %>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-3">
                                    <h6 class="mb-0">Email</h6>
                                </div>
                                <div class="col-sm-9 text-secondary">
                                    <%= user.email %>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-3">
                                    <h6 class="mb-0">Data Inregistrarii: <h6>
                                </div>
                                <div class="col-sm-9 text-secondary">
                                    <%= user.register_date %>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>
    </div>

</body>

<footer>
    
</footer>



</html>

问题出在快速路线上。 res.renderres.redirect 之后执行,代码部分类似于以下代码:

  if (req.session.user) {
    res.redirect("/profile");
  }
  res.render("register", { user: req.session.user, online });

相反,使用 else 以便 res.render 仅在没有用户会话时执行:

  if (req.session.user) {
    res.redirect("/profile");
  }
  else {
    res.render("register", { user: req.session.user, online });
  }