javascript - nodejs - 奇怪的 "Can' t 在发送后设置 header “案例

标签 javascript node.js express

我的 NodeJs/Express 应用程序发生了奇怪的发送后无法设置 header 崩溃。

崩溃的请求:POST/auth/form

服务器端如何处理请求

app.js

[...]
var auth_route = require('./routes/auth');
app.use('/auth', auth_route );
[...]

auth.js

var AuthController = require('../controller/auth_controller');

[...]

router.post("/form", function(req, res) {
    [...]
    auth_ctrl.form_login(username, password);
});

auth_controller.js

AuthController.prototype.form_login = function(username, password) {
    _this.user_model.get_by_username(username, function(user) {
        if (user == null)
            return (Response.send_204(_this.res, "User not found"))
        password.isTheSame(password, user.password, function(err, res) {
            if (err)
                return (Response.send_error_response(_this.res, 500, "Internal server error occured, sorry about that.."));
            if (!res)
                return (Response.send_error_response(_this.res, 401, "Wrong password"));
            // Crash seems to happen on the above 401 response which is the 67th lines of my auth_controller file (cf. callstack bellow)
            _this.start_user_session(user, function(err) {
                if (err) 
                    return (Response.send_error_response(_this.res, 500, "Internal server error"));
                return (Response.send_200(_this.res, "You are logged!"));
            })
        });
    })
}

Response.send_error_response 源代码(如果需要)

function send_error_response(res, code, message, missing_fields) {
    [..]

    res.header('Content-Type', 'application/json')
    res.status(code).send(JSON.stringify({
        [..]
    }));
}

调用堆栈跟踪

POST /auth/form 401 2.408 ms - -
_http_outgoing.js:356
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (C:\Users\ME\dev\app\node_modules\express\lib\response.js:719:10)
    at Object.send_error_response (C:\Users\ME\dev\app\core\lib\Response.Library.js:30:6)
    at C:\Users\ME\dev\app\controller\auth_controller.js:67:22

如何让这次崩溃发生

我不断按下输入按钮,它会从同一来源发送大量请求。

这似乎发生在密码回调函数内部......

有什么建议吗?提前致谢!

最佳答案

我的猜测是,您的 AuthController 实现会执行以下操作:

var _this;
function AuthController(req, res) {
  this.req = req;
  this.res = res;
  _this = this;
}

这将_this“提升”为(模块范围的)全局变量,对于发布到/auth/form的每个请求,该全局变量都会被覆盖。如果快速连续发送其中两个请求,您最终可能会遇到使用同一 _this 多次发送响应的情况,这将导致您收到的错误:

  • 请求 1 传入,_this 指向其 Controller 实例
  • 请求 2 到来,_this 被覆盖以指向 Controller 实例
  • 请求 1 已完成并使用属于请求 2 的 _this 发回响应
  • 请求 2 已完成并使用相同的 _this 发回响应,导致错误

所以,不要使用全局变量,而是使用this:

AuthController.prototype.form_login = function(username, password) {
    this.user_model.get_by_username(username, function(user) {
      ...
    });
};

如果愿意的话,您始终可以创建一个函数范围的变量来保存对其的引用:

AuthController.prototype.form_login = function(username, password) {
    var _this = this;
    _this.user_model.get_by_username(username, function(user) {
      ...
    });
};

关于javascript - nodejs - 奇怪的 "Can' t 在发送后设置 header “案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43934310/

相关文章:

javascript - ASP.NET 以编程方式从 AJAX 插入表行

javascript - 删除多个文档并将它们传递给回调

javascript - 如何使用 Node-express 将页面 B 通过表单发布的数据渲染到页面 A?

java - Jax-RS 和 Xmlhttp 通信

javascript - 将循环的输出复制到 DIV

node.js - 非身份验证 Web 应用程序中的处理和设计 session 部分

node.js - 从nodejs推送到kafka主题时获取消费者的空值?

node.js - 在多个地方需要模块并创建对象

javascript - 全局常量可以在 JavaScript 中声明吗?

node.js - Node : missing ) after argument list