【发布时间】: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