发送到客户端后无法设置标头将会话数据表达为 ejs html

如何解决发送到客户端后无法设置标头将会话数据表达为 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 文件中打印(例如:,),我不知道还能做什么,如果有人有更好的主意或一些提示/技巧会很有用,还是谢谢!

快速路线:

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",next) => {
  if (req.session.user) {
    res.redirect("/profile");
  }
  res.render("register",{ user: req.session.user,online });
});
 
// Get
router.get("/",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",online });
});
 
router.get("/error",next) => {
  if (req.session.user) {
    res.render("error",online });
  }
  res.render("error",online });
});
 
router.get("/profile",next) => {
  if (req.session.user) {
    online = req.session.user.username;
    res.render("userprofile",online });
    return res.status(400).json({
      status: "error",error: "req body cannot be empty",});
  }
  res.redirect("/index");
  return res.status(400).json({
    status: "error",});
});
 
router.get("/logout",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",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",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;

用户注册/登录逻辑:

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,email) VALUES ('${username}','${password}','${email}')`;

        pool.query(sql,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",online });
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-