【问题标题】:Express.js Rout Redirect Error: Can't set headers after they are sentExpress.js Rout 重定向错误:发送后无法设置标头
【发布时间】:2020-04-30 17:41:06
【问题描述】:

我不确定为什么会收到此错误,“错误:发送后无法设置标头。”它是基于 express.js 构建的简单 API,它将检查用户是否登录,如果用户未登录,它只会将用户带到登录页面。

当你看下面从fetch(authApiUrl, config)开始的代码时,如果用户登录,它会给出状态200。如果用户没有登录,它会给出状态401,它会进入“else”声明并启动redirectToAccountSignin(request, response, wwwS);

然后它将进入redirectToAccountSignin 函数。到目前为止,当我运行这段代码时,它确实进入了redirectToAccountSignin 函数,但我相信它会在response.redirect(wwwS + '/account/signin?method=initialize&TARGET=' + encodedTargetUrl); 上引发错误。

我的“重定向”方法有问题吗?我究竟做错了什么?谁能帮我解决这个问题?

提前谢谢你。

const fetch = require("node-fetch");
const splunkLogFormat = require('./logUtilities');

function authenticate(request, response, next, successCallback, configuration) {
  // get environment for URL call and grab from environment json
  const appName = !!configuration.appName ? configuration.appName : 'micro-server-app';
  const runtimeEnvironment = !!configuration.environment ? configuration.environment : 'dev';

  const logPreamble = splunkLogFormat(appName, 'authenticate');
  const wwwS = !!environments && !!environments[runtimeEnvironment] && environments[runtimeEnvironment].www_s;

  const authApiUrl = wwwS + '/api/auth/login/check';
  const headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    cookie: request.headers.cookie
  };
  const method = 'GET';
  const config = { headers, method };
  fetch(authApiUrl, config)
    .then(authResponse => {
      const status = authResponse.status;
      if (status === 200) {
        successCallback(request, response, next);
      } else {
        redirectToAccountSignin(request, response, wwwS);
      }
    })
    .catch(error => {
      redirectToAccountSignin(request, response, wwwS);
    });
};

function redirectToAccountSignin(request, response, wwwS) {
  const hostname = !!request && request.hostname;
  const protocol = 'https://';
  const url = !!request && request.originalUrl;
  const encodedTargetUrl = encodeURIComponent(protocol + hostname + url);

  response.redirect(wwwS + '/account/signin?method=initialize&TARGET=' + encodedTargetUrl);
  response.end();
};

module.exports = authenticate;

【问题讨论】:

    标签: javascript node.js api express fetch


    【解决方案1】:

    您确定要在res.redirect() 之后使用res.end() 吗? https://stackoverflow.com/a/54874227/4208845在那之前你在写什么?

    【讨论】:

    • res.end() 放在res.redirect 之后应该不是问题。我实际上尝试删除 res.end() 但这并没有解决我的问题。我要做的就是在用户进入该功能时重定向res.redirect() 内的url 用户。
    猜你喜欢
    • 2015-08-10
    • 1970-01-01
    • 2016-05-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多