javascript - 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;
解决方案
您确定要使用res.end()
afterres.redirect()
吗?https://stackoverflow.com/a/54874227/4208845在那之前你在写什么?
推荐阅读
- python - 使用python替换所有换行符
- matlab - X轴上的Matlab日期帮助
- node.js - 默认sails web应用程序中的sails.helpers函数来自哪里
- java - FullTextEntityManager 在部署war文件之前索引数据库中所有表的问题
- ruby - Error: unknown error: DevToolsActivePort file doesn't exist, when executing ruby script with watir
- python-2.7 - 将行数组转换为pyspark中的字符串数组
- javafx - 在 Mac 中使用组合框时出现 NullPointerException
- r - 如何在另一个向量中使用大于 x 的元素创建向量
- reactjs - 反应事件对象
- symfony - 是否需要为每个请求/响应更新 JWT 令牌中的 CSRF 令牌?