node.js - 如何更改中间件 node.js 中的响应标头
问题描述
我在谷歌搜索了很多这个问题,但不幸的是所有解决方案都不适合我。
我需要向响应标头 isAuth 添加特殊属性,该属性必须为真。我尝试使用set、setHeader、append等。但是所有这些方法都不适合我
我的中间件:
export const isAuthenticated = async (req, res, next) => {
res.set('isAuth', true);
next();
}
我的控制器,我想在其中读取此标头属性 isAuth:
import httpStatus from 'http-status';
import { RequestHandler } from 'express';
export const controller: RequestHandler = async (req: Request<ParamsDictionary, any, any, QueryString.ParsedQs>, res: Response<any>) => {
const isAuth = res.header('isAuth');
console.log('isAuth: ', isAuth)
};
在控制器中 isAuth 变量不正确,它等于
<ref *2> ServerResponse {
_events: [Object: null prototype] {
finish: [ [Function: bound resOnFinish], [Function: onevent] ],
end: [Function: onevent]
},
_eventsCount: 2,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: <ref *1> Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: false
},
_events: [Object: null prototype] {
end: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Array],
close: [Array],
drain: [Function: bound socketOnDrain],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause]
},
_eventsCount: 8,
_maxListeners: undefined,
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
errored: null,
closed: false,
closeEmitted: false
},
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: Server {
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 0,
keepAliveTimeout: 5000,
maxHeadersCount: null,
headersTimeout: 60000,
requestTimeout: 0,
_connectionKey: '6::::3000',
[Symbol(IncomingMessage)]: [Function: IncomingMessage],
[Symbol(ServerResponse)]: [Function: ServerResponse],
[Symbol(kCapture)]: false,
[Symbol(async_id_symbol)]: 189
},
_server: Server {
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [TCP],
_usingWorkers: false,
_workers: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 0,
keepAliveTimeout: 5000,
maxHeadersCount: null,
headersTimeout: 60000,
requestTimeout: 0,
_connectionKey: '6::::3000',
[Symbol(IncomingMessage)]: [Function: IncomingMessage],
[Symbol(ServerResponse)]: [Function: ServerResponse],
[Symbol(kCapture)]: false,
[Symbol(async_id_symbol)]: 189
},
parser: HTTPParser {
'0': [Function: bound setRequestTimeout],
'1': [Function: parserOnHeaders],
'2': [Function: parserOnHeadersComplete],
'3': [Function: parserOnBody],
'4': [Function: parserOnMessageComplete],
'5': [Function: bound onParserExecute],
'6': [Function: bound onParserTimeout],
_headers: [],
_url: '',
socket: [Circular *1],
incoming: [IncomingMessage],
outgoing: null,
maxHeaderPairs: 2000,
_consumed: true,
onIncoming: [Function: bound parserOnIncoming],
[Symbol(resource_symbol)]: [HTTPServerAsyncResource]
},
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular *2],
_peername: { address: '::1', family: 'IPv6', port: 59763 },
[Symbol(async_id_symbol)]: 238,
[Symbol(kHandle)]: TCP {
reading: true,
onconnection: null,
_consumed: true,
[Symbol(owner_symbol)]: [Circular *1]
},
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_header: null,
_keepAliveTimeout: 5000,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: [],
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
errorEmitted: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
errored: null,
closed: false,
closeEmitted: false,
defaultEncoding: 'utf8',
awaitDrainWriters: null,
multiAwaitDrain: false,
readingMore: false,
decoder: null,
encoding: null,
[Symbol(kPaused)]: false
},
_events: [Object: null prototype] { end: [Function: clearRequestTimeout] },
_eventsCount: 1,
_maxListeners: undefined,
socket: <ref *1> Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular *2],
_peername: [Object],
[Symbol(async_id_symbol)]: 238,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: {
authorization: '5ac750e0-d2c6-4673-b022-4674f8c62df3',
'user-agent': 'PostmanRuntime/7.26.10',
accept: '*/*',
'postman-token': '3e73d366-8e2e-493b-a01e-42ba2a7969ea',
host: 'localhost:3000',
'accept-encoding': 'gzip, deflate, br',
connection: 'keep-alive',
'content-type': 'application/x-www-form-urlencoded',
'content-length': '72'
},
rawHeaders: [
'authorization',
'5ac750e0-d2c6-4673-b022-4674f8c62df3',
'User-Agent',
'PostmanRuntime/7.26.10',
'Accept',
'*/*',
'Postman-Token',
'3e73d366-8e2e-493b-a01e-42ba2a7969ea',
'Host',
'localhost:3000',
'Accept-Encoding',
'gzip, deflate, br',
'Connection',
'keep-alive',
'Content-Type',
'application/x-www-form-urlencoded',
'Content-Length',
'72'
],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '/reserve/6093e5a0f876203e79de259a',
method: 'POST',
statusCode: null,
statusMessage: null,
client: <ref *1> Socket {
connecting: false,
_hadError: false,
_parent: null,
_host: null,
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 8,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Server],
_server: [Server],
parser: [HTTPParser],
on: [Function: socketListenerWrap],
addListener: [Function: socketListenerWrap],
prependListener: [Function: socketListenerWrap],
_paused: false,
_httpMessage: [Circular *2],
_peername: [Object],
[Symbol(async_id_symbol)]: 238,
[Symbol(kHandle)]: [TCP],
[Symbol(kSetNoDelay)]: false,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(RequestTimeout)]: undefined
},
_consuming: true,
_dumped: false,
next: [Function: next],
baseUrl: '/group-workouts',
originalUrl: '/group-workouts/reserve/6093e5a0f876203e79de259a',
_parsedUrl: Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/reserve/6093e5a0f876203e79de259a',
path: '/reserve/6093e5a0f876203e79de259a',
href: '/reserve/6093e5a0f876203e79de259a',
_raw: '/reserve/6093e5a0f876203e79de259a'
},
params: { id: '6093e5a0f876203e79de259a' },
query: {},
res: [Circular *2],
body: {
userId: '123',
dateStart: '123',
dateFinish: '123',
cryptogram: '123',
paymentDataId: '123'
},
_body: true,
length: undefined,
_startAt: [ 676465, 618613151 ],
_startTime: 2021-05-07T13:12:18.733Z,
_remoteAddress: '::1',
route: Route { path: '/reserve/:id', stack: [Array], methods: [Object] },
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
},
locals: [Object: null prototype] {},
_startAt: undefined,
_startTime: undefined,
writeHead: [Function: writeHead],
__onFinished: [Function: listener] { queue: [ [Function: logRequest] ] },
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
'0': [ '0', 'i' ],
'1': [ '1', 's' ],
'2': [ '2', 'M' ],
'3': [ '3', 't' ],
'4': [ '4', 's' ],
'5': [ '5', 'A' ],
'6': [ '6', 'u' ],
'7': [ '7', 't' ],
'8': [ '8', 'h' ],
'access-control-allow-origin': [ 'Access-Control-Allow-Origin', '*' ],
'x-dns-prefetch-control': [ 'X-DNS-Prefetch-Control', 'off' ],
'x-frame-options': [ 'X-Frame-Options', 'SAMEORIGIN' ],
'strict-transport-security': [
'Strict-Transport-Security',
'max-age=15552000; includeSubDomains'
],
'x-download-options': [ 'X-Download-Options', 'noopen' ],
'x-content-type-options': [ 'X-Content-Type-Options', 'nosniff' ],
'x-xss-protection': [ 'X-XSS-Protection', '1; mode=block' ]
}
}
太奇怪了。谁能帮我?我完全不明白这里有什么问题。
将不胜感激任何帮助
解决方案
我相信你可以做到res.locals.auth = true
,你可以在 express 文档中找到更多细节:http:
//expressjs.com/en/api.html#res.locals
推荐阅读
- sql - SQL:无效的列名在一个查询中有效,但在另一个查询中无效
- azure-ad-b2c - 间歇性 Azure AD B2C 异常:IDX10614:AsymmetricSecurityKey.GetSignatureFormater() 引发异常
- java - 将远程 json 文件加载到 Android 应用程序的简单方法?(视频视图)
- flutter - 颤振如何使模态路线动画从底部开始
- html - HTML 电子邮件签名在不同的电子邮件客户端上呈现不同/不正确
- encoding - 打包的电子应用程序中的字符编码错误
- swift - MacOS - 如何以编程方式计算 Swift 中图像的字节数?
- firebase - 如何实时显示 Firebase 列表?
- python - 如果任何并行线程退出,如何退出 Python 进程?
- python-3.x - 使用线程停止无限功能