首页 \ 问答 \ 错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)

错误:发送后无法设置标题。(Error: Can't set headers after they are sent. authentication system)

我想用mysql连接编写一个小的身份验证应用程序,并且我始终得到这个错误,但我需要这种方式。
我想发送一个响应,如果客户端/管理员,如果他不是管理员,如果他是,应该呈现管理员。

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
const admin = require("./routes/admin");
const session = require("express-session");
var app = express();
app.set("trust proxy", 1);
app.use(session({
  secret: "asdf",
  resave: false,
  cookie: {
    maxAge: 120000
  },
  saveUninitialized: false
}));
function checkIfLoggedin(req,res,next){
  if(!(req.originalUrl === "/") && !req.session.loggedIn){
    res.redirect('/');
    return;
  }
  next();
};


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(checkIfLoggedin);
app.use('/', index);
app.use("/admin", admin);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;

index.js

var express = require('express');
var router = express.Router();
const bcrypt = require('bcrypt-nodejs');
var dbPassword;
import mysql from "mysql";
//
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {});
});
router.post('/', function(req,res,next) {
  console.log("1");
  const enteredUsername = req.body.username;
  const enteredPassword = req.body.password;
  const con = mysql.createConnection({
    host: "localhost",
    user: "user",
    password: "pass",
    database: "db"
  });
  con.query('SELECT * FROM users WHERE username = ?;', [`${enteredUsername}`], (error, results, fields) => {
    if (results.length > 0) {
      console.log("2");
      console.log(error);
      let dbPassword = results[0].password;
      bcrypt.compare(enteredPassword, dbPassword, (err,response) => {
        console.log(err);
        console.log(response);
        console.log("3");
        if (response == true) {
          req.session.user = {
            userId: results[0].userId,
            username: results[0].username,
            isAdmin: results[0].isAdmin,
          };
          req.session.loggedIn = true;
          console.log("file");
          if (req.session.user.isAdmin) {
            res.redirect("/admin");
          }
          else{
            res.redirect("/file/" + req.session.user.userId);
          }

        }
        else{
          req.session.loggedIn = false;

          console.log("false");
          res.send("Wrong password");
        }
      });
    }
    else{
      res.send("Wrong Data");
    }
  });
});
module.exports = router;

admin.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  if (!req.session.user.isAdmin) {
    res.send("Du bist kein Admin!");
  }
  res.render("admin");

});

module.exports = router;

index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>Costufi</title>
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link type="text/css" rel="stylesheet" href="stylesheets/materialize.min.css"  media="screen,projection"/>
  </head>
  <body>
    <main>
      <center>
        <div class="container">
          <div class="z-depth-2" style="display: inline-block; padding: 20px 50px 10px 50px; margin-top: 15%;">
            <form class="col s12" action="/" method="post">
              <div class="row">
                <h4>Login</h4>
                <div class="input-field col s12">
                  <input type="text" name="username" id="username" class="validate">
                  <label for="username">Username</label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <input type="password" name="password" id="password" class="validate">
                  <label for="password">PassworD</label>
                </div>
              </div>
              <div class="row">
                <button class="left btn waves-effect waves-light indigo darken-2" type="submit" name="send">Login
                  <i class="material-icons right">send</i>
              </div>
            </form>
          </div>
        </div>
      </center>
    </main>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/materialize.min.js"></script>
  </body>
</html>

I want to write a little authentication app with mysql connection and I get this error all the time, but I need it this way.
I want to send a response if the client gets /admin if he is not an admin and if he is, admin should be rendered.

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
const admin = require("./routes/admin");
const session = require("express-session");
var app = express();
app.set("trust proxy", 1);
app.use(session({
  secret: "asdf",
  resave: false,
  cookie: {
    maxAge: 120000
  },
  saveUninitialized: false
}));
function checkIfLoggedin(req,res,next){
  if(!(req.originalUrl === "/") && !req.session.loggedIn){
    res.redirect('/');
    return;
  }
  next();
};


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(checkIfLoggedin);
app.use('/', index);
app.use("/admin", admin);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;

index.js

var express = require('express');
var router = express.Router();
const bcrypt = require('bcrypt-nodejs');
var dbPassword;
import mysql from "mysql";
//
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', {});
});
router.post('/', function(req,res,next) {
  console.log("1");
  const enteredUsername = req.body.username;
  const enteredPassword = req.body.password;
  const con = mysql.createConnection({
    host: "localhost",
    user: "user",
    password: "pass",
    database: "db"
  });
  con.query('SELECT * FROM users WHERE username = ?;', [`${enteredUsername}`], (error, results, fields) => {
    if (results.length > 0) {
      console.log("2");
      console.log(error);
      let dbPassword = results[0].password;
      bcrypt.compare(enteredPassword, dbPassword, (err,response) => {
        console.log(err);
        console.log(response);
        console.log("3");
        if (response == true) {
          req.session.user = {
            userId: results[0].userId,
            username: results[0].username,
            isAdmin: results[0].isAdmin,
          };
          req.session.loggedIn = true;
          console.log("file");
          if (req.session.user.isAdmin) {
            res.redirect("/admin");
          }
          else{
            res.redirect("/file/" + req.session.user.userId);
          }

        }
        else{
          req.session.loggedIn = false;

          console.log("false");
          res.send("Wrong password");
        }
      });
    }
    else{
      res.send("Wrong Data");
    }
  });
});
module.exports = router;

admin.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  if (!req.session.user.isAdmin) {
    res.send("Du bist kein Admin!");
  }
  res.render("admin");

});

module.exports = router;

index.ejs

<!DOCTYPE html>
<html>
  <head>
    <title>Costufi</title>
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <link type="text/css" rel="stylesheet" href="stylesheets/materialize.min.css"  media="screen,projection"/>
  </head>
  <body>
    <main>
      <center>
        <div class="container">
          <div class="z-depth-2" style="display: inline-block; padding: 20px 50px 10px 50px; margin-top: 15%;">
            <form class="col s12" action="/" method="post">
              <div class="row">
                <h4>Login</h4>
                <div class="input-field col s12">
                  <input type="text" name="username" id="username" class="validate">
                  <label for="username">Username</label>
                </div>
              </div>
              <div class="row">
                <div class="input-field col s12">
                  <input type="password" name="password" id="password" class="validate">
                  <label for="password">PassworD</label>
                </div>
              </div>
              <div class="row">
                <button class="left btn waves-effect waves-light indigo darken-2" type="submit" name="send">Login
                  <i class="material-icons right">send</i>
              </div>
            </form>
          </div>
        </div>
      </center>
    </main>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="js/materialize.min.js"></script>
  </body>
</html>

原文:https://stackoverflow.com/questions/48270822
更新时间:2024-05-17 07:05

最满意答案

你仍然需要在图上做很多张量操作来预测某些东西。 因此GPU仍然可以为推理提供性能改进。 看看这篇nvidia论文 ,他们没有在TF上测试过他们的东西,但它仍然是相关的:

我们的结果表明,GPU提供了最先进的推理性能和能效,使其成为任何想要在现场部署经过训练的神经网络的人的首选平台。 特别是,Titan X的性能比16核Xeon E5 CPU高出5.3到6.7倍,同时能效提高了3.6到4.4倍。

关于如何部署模型,请查看TF服务


You still need to do a lot of tensor operations on the graph to predict something. So GPU still provides performance improvement for inference. Take a look at this nvidia paper, they have not tested their stuff on TF, but it is still relevant:

Our results show that GPUs provide state-of-the-art inference performance and energy efficiency, making them the platform of choice for anyone wanting to deploy a trained neural network in the field. In particular, the Titan X delivers between 5.3 and 6.7 times higher performance than the 16-core Xeon E5 CPU while achieving 3.6 to 4.4 times higher energy efficiency.

Regarding how to deploy your model, take a look at TF serving

相关问答

更多
  • 这取决于您的查询工作量。 这是一种简单的数据压缩形式。 减少回答给定查询所需的一组数据可以提高性能。 另一方面,你在许多地方引入开销。 这是一个权衡。 如果你想检索这些列的值,你现在需要加入。 DML也变慢了。 由于名称列可能相当小,因此很难想象会受益于此方案的查询工作负载。 DATA_COMPRESSION和备份压缩可以替代。 他们做出了非常不同的折衷。 只是为了证明你的方案有价值:想象一下很长的名字和一个巨大的(TB大小的)表格。 节省的空间将很重要,因为名称很少。 It depends on your ...
  • 在这种情况下,我找到了一种提高速度的方法。 我写了一个多线程版本的memcpy,拆分要在线程之间复制的区域。 以下是使用与上述相同的时间码,设置块大小的一些性能缩放数字。 我不知道性能,特别是对于这个小尺寸的块,可以扩展到这么多线程。 我怀疑这与本机上大量的内存控制器(16)有关。 Performance (10000x 4MB block memcpy): 1 thread : 1826 MB/sec 2 threads: 3118 MB/sec 3 threads: 4121 MB/sec ...
  • 我似乎找不到一种将评论标记为帖子答案的方法,因此我将指出最好的答案是由softwarenwebie7331 。 I cant seem to find a way to mark a comment as the answer to a post, so I will state that the best answer was given by softwarenwebie7331.
  • 你仍然需要在图上做很多张量操作来预测某些东西。 因此GPU仍然可以为推理提供性能改进。 看看这篇nvidia论文 ,他们没有在TF上测试过他们的东西,但它仍然是相关的: 我们的结果表明,GPU提供了最先进的推理性能和能效,使其成为任何想要在现场部署经过训练的神经网络的人的首选平台。 特别是,Titan X的性能比16核Xeon E5 CPU高出5.3到6.7倍,同时能效提高了3.6到4.4倍。 关于如何部署模型,请查看TF服务 You still need to do a lot of tensor ope ...
  • 尝试限制带有索引的列上的WHERE子句的查询。 例如: SELECT * FROM table WHERE id >= 38975901200 LIMIT 1 更新:我想也许你甚至不需要数据库? 通过计算类似15824293949 / 177901和15824293949 % 177901值,可以找到两个图像的第n个组合。 我想你可以写一个查询: SELECT (15824293949 / 177901) AS img_id1, (15824293949 MOD 177901) AS img_id2 如 ...
  • 最大的问题是语言依赖性。 您可以理解某种语言并阅读例如英语网站这一事实并不意味着您能够生成语义正确的句子。 所以对大多数人来说,这可能会变成一种烦恼。 The biggest problem with this is language dependency. The fact that you can understand a language and read for example an English site does not mean you are able to produce semanti ...
  • 想一想什么时候在现实生活中平行一些东西是值得的。 自始至终坐下来做一个工作什么时候更好?雇用二十个人的时候更好? 这个作品是固有的可并行还是固有的连续? 有些工作根本不可并行:九个女人不能在一个月内共同生产一个婴儿。 有些工作是可并行的,但结果很糟糕:你可以雇用二十个人,并为他们分配五十页的战争与和平给你看,然后让他们每人写一篇文章的二十分之一,把所有的散文片段粘在一起,提交论文; 这不太可能导致好成绩。 有些工作是非常平行的:20个铲子的人可以比一个人快得多挖洞。 如果工作本质上是可并行化的,那么并行化是 ...
  • 我们将创建一个函数,返回最新的元素对,它们总计所需的总和: function find_pair(l, s) { var min_indexes = {}; for (var i = 0; i < l.length; i++) { var a = l[i]; if ((s - a) in min_indexes) return [s - a, a]; if (!(a in min_indexes)) ...
  • 作曲家可以立即开箱即用 - 在一个或多个子目录内建立所有类别的列表。 当实际自动加载它们时,还有一些可选的优化可用于缓存文件的(非)存在,以便不需要进一步的检查。 这些优化几乎总是只在生产中有用,而部署受到控制。 Based on suggestions of Elias Soares and Mark Baker I rewrite my code to use file mapping based on a php array. To create and recreate the php automa ...
  • 我相信你遇到的问题是你的代码将整个文件读入内存。 从文件中流式传输线条应该可以提高性能。 我试了一下并评估了多个模块( byline , split , readline )来处理换行的读取。 readline在三者中表现最好,所以这就是我要展示的。 这是一个我从文件中读取的示例,每行大写,然后将结果写入另一个文件。 如果您在解析数据后不关心使用数据,只需忽略所有的rs代码。 const fs = require('fs') const readline = require('readline') cons ...

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)