首页 > 解决方案 > Express.js Rout 重定向错误:发送后无法设置标头

问题描述

我不确定为什么会收到此错误,“错误:发送后无法设置标头。” 它是基于 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;

标签: javascriptnode.jsapiexpressfetch

解决方案


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


推荐阅读