Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - node.js收到“ ERR_HTTP_HEADERS_SENT”错误(node.js getting 'ERR_HTTP_HEADERS_SENT' error)

this is my ejs code in node.js, and currently i keep getting this error(这是我在node.js中的ejs代码,目前我一直在收到此错误)

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) at ServerResponse.header (C:\Users\DomKim\Desktop\workspaceForNode\node_modules\express\lib\response.js:771:10) at ServerResponse.location (C:\Users\DomKim\Desktop\workspaceForNode\node_modules\express\lib\response.js:888:15) at ServerResponse.redirect (C:\Users\DomKim\Desktop\workspaceForNode\node_modules\express\lib\response.js:926:18) at assertRedirection (C:\Users\DomKim\Desktop\workspaceForNode\exsignon\sso\sso_assert.ejs:330:13) at processTicksAndRejections (internal/process/task_queues.js:93:5) { code: 'ERR_HTTP_HEADERS_SENT'(错误[ERR_HTTP_HEADERS_SENT]:将标头发送到ServerResponse.header的ServerResponse.setHeader(_http_outgoing.js:485:11)(C:\ Users \ DomKim \ Desktop \ workspaceForNode \ node_modules \ express \ lib \在ServerResponse.redirect(C:\ Users \ DomKim \)的ServerResponse.location(C:\ Users \ DomKim \ Desktop \ workspaceForNode \ node_modules \ express \ lib \ response.js:888:15)中的response.js:771:10)在assertRedirection(C:\ Users \ DomKim \ Desktop \ workspaceForNode \ exsignon \ sso \ sso_assert.ejs:330:13)的assertRedirection(Desktop \ workspaceForNode \ node_modules \ express \ lib \ response.js:926:18)处(processTicksAndRejections)(内部/进程) /task_queues.js:93:5){代码:“ ERR_HTTP_HEADERS_SENT”)

everything works so fine just before the redirection is called for the federation,(在为联邦调用重定向之前,一切工作都很好,)

can anyone please help me with this code!(谁能帮我这个代码!)

would be really appreciated(将不胜感激)

<%



function replaceAll(str, searchStr, replaceStr) {
  return str.split(searchStr).join(replaceStr);
}
%>

<%

const AUTH_URL = "/svc/tk/Auth.do";
const AUTH_RESOLVE_URL = "/svc/tk/AuthResolve.do";
const AUTH_ASSERT_URL = "/svc/tk/AuthAssert.do";
const AUTH_FEDERATE_URL = "/svc/tk/AuthFederate.do";
const LOGIN_URL = "/svc/tk/Login.do";
const LOGOUT_URL = "/svc/tk/SLO.do";

const RELAY_STATE_NAME = "RelayState";
const ID_NAME = "id";
const SECRET_NAME = "secret";
const NAMEID_NAME = "nameId";
const STATUS_NAME = "status";
const TARGET_ID_NAME = "targetId";
const DATA_NAME = "data";
const AC_NAME = "ac";
const IFA_NAME = "ifa";
const TOKEN_NAME = "t";
const SP_ID_NAME = "spid";

const SUCCESS = "success";
const FAILURE_CAUSE = "failureCause";

const SSO_SESSION_NAME = "eXSignOn.session.userid";
const SSO_SESSION_ANONYMOUSE = "anonymous";
const SSO_SESSION_ANONYMOUSE_IDENTIFY = "anonymous_identify";

const SSO_ASSERT_NAME = "eXSignOn.assert.userid";
const SSO_REMEMBERME = "sso_remember_me";

%><%


function encode(data){
  if(data == null || ""==data.trim()) {
      return "";

  }

  try {
      return encodeURI(data);
  } catch(e) {
      return encodeURIComponent(data);
  }
}





function generateUrl (idpUrl, subUrl) {
    if((idpUrl == null || ""==idpUrl.trim()) && (subUrl == null || ""==subUrl.trim())) {
        return null;
    }

    let url = idpUrl
    if(!idpUrl.endsWith("/")) {
        url += "/";
    }

    url += subUrl;

    url = url.replace(//+/g, "/");

    if(url.startsWith("http:/") && !url.startsWith("http://")) {
        url = url.replace(/^http://, "http://");
    } else if(url.startsWith("https:/") && !url.startsWith("https://")) {
        url = url.replace(/^https://, "https://");
    }

    return url;
}




function generateParam(param){
    var paramStr = "";

    for (var [key, value] of param.entries()) {
        paramStr += key + "=" + value + '&';
      }

    return paramStr;
}

// getconnection function ? qs ? ??? value ??
function generateQueryString(param) {
    var paramStr = "{";

    for (var [key, value] of param.entries()) {
        paramStr += key + ":'" + value + "',";
      }
      paramStr = paramStr.substring(0, paramStr.length - 1);
      param+='}';

    return paramStr;
}





function generateUrlWithParam(idpUrl,subUrl,param){
  var url = generateUrl(idpUrl, subUrl);

  if(url == null) {
      return null;
  }

  var paramStr = generateParam(param);

  return url + "?" + paramStr;
}





async  function getConnection(url,param) {
     var queryStr = generateQueryString(param);
     var result ;
      console.log();


      let OPTIONS = { method: 'POST',
        url: url,
        headers:
         {
           Accept: '*/*',
           'User-Agent': 'PostmanRuntime/7.20.1',
           'Content-Type': 'application/x-www-form-urlencoded' },
        form:
         { id: 'testing',secret: 'XRRpYIoMtaJC8hFLfUN7Bw==',nameId: 'tomato'} };



   await  request(OPTIONS).then(function(body){


               result = JSON.parse(body);
              console.log('result in rquest.post : '+result);

       }).catch(function(err){
            console.log('error! : ' + err);
            return;
       });
       console.log('result out rquest.post : '+result);
       return result;
 }

 async function httpRequest(url, paramMap){
     let requestUrl = null;
     let conn = null;
     let result = null;
     let out = null;
     let writer = null;
     let reader = null;


     try {
         result = await getConnection(url,paramMap);
         console.log(result);


     } catch(e) {
         console.log(e);
         return;
     }
     return result;
 }


 function addContextPath(path){
   var ctxPath = argv.contextPath  ||  "/";

   var relativePath = ctxPath + "/" + path;
   relativePath = replaceAll(relativePath, "///"||"//", "/");
   console.log(relativePath);

   return relativePath;
 }


%>


<%

/*
? ??? ???? ???? ????(ID) ? ????? ?? ?? ????? ?? ???? ????.
?, ?????? ID?? ??? ????? ??? ??? ? ?? ????.
*/

//??? ?????? ???? ?? ???

var session = req.session;
console.log('ssan '+ session[SSO_ASSERT_NAME]);
var nameId = session[SSO_ASSERT_NAME];
session[SSO_ASSERT_NAME]= null;
console.log('ssan23 '+ nameId);


console.log(req.body);
var relayState = req.body[RELAY_STATE_NAME];

var targetSp = req.body[TARGET_ID_NAME];

var rememberMe = req.body[SSO_REMEMBERME];


if(nameId == null || ""== nameId.trim()) {
     res.send('400', "user id not found.");
     return;
}

else if(targetSp == null || ""== targetSp.trim()) {
    res.send('403', "forbidden.");
    return;
}


var paramMap = new Map();
paramMap.set(ID_NAME, SP_ID);
paramMap.set(SECRET_NAME, SP_SECRET);
paramMap.set(NAMEID_NAME, nameId);

var url = generateUrl(IDP_URL, AUTH_ASSERT_URL);




async function assertRedirection(url, paramMap){
  try {
    var obj = await httpRequest(url, paramMap);
    console.log(obj);
    var success = obj[STATUS_NAME];
  console.log(success);

    if(SUCCESS==success) {
        var data = obj[DATA_NAME];
        console.log(data);
        var fedParam = new Map();
        fedParam.set(TOKEN_NAME, data);
        fedParam.set(ID_NAME, SP_ID);
        fedParam.set(TARGET_ID_NAME, targetSp);
        fedParam.set(RELAY_STATE_NAME, relayState);
        fedParam.set(SSO_REMEMBERME, rememberMe);

        var federateUrl = generateUrlWithParam(IDP_URL, AUTH_FEDERATE_URL, fedParam);
        console.log(federateUrl);


        res.redirect(federateUrl);

        return;
    } else {
        var errCode = obj[FAILURE_CAUSE];

        var param = new Map();
        param.set(FAILURE_CAUSE, errCode);
        param.set(RELAY_STATE_NAME, relayState);

        var failUrl = addContextPath(TOKEN_VERIFY_FAIL_URL);
        await res.redirect(failUrl + "?" + generateParam(param));

        return;
    }


  } catch(e) {
      console.log(e);
      return;
  }



}
assertRedirection(url, paramMap);


%>
  ask by Hyun Jong Kim translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

res.headerSent is a boolean value that indicates whether the headers have already been sent to the client.(res.headerSent是一个布尔值,指示标头是否已发送到客户端。)

Add this check before sending response and log through console which response is going.(在发送响应之前添加此检查,并通过控制台记录响应的内容。)
if(res.headersSent) {
console.log("Check 1");
res.redirect(federateUrl);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...