如何更改中间件node.js中的响应头
我在谷歌上搜索了很多这个问题,但不幸的是,所有的解决方案都不适合我 我需要向响应头isAuth添加特殊属性,该属性必须为true。我试着使用set、setHeader、append等。但所有这些方法对我都不起作用 我的中间件:如何更改中间件node.js中的响应头,node.js,typescript,express,middleware,Node.js,Typescript,Express,Middleware,我在谷歌上搜索了很多这个问题,但不幸的是,所有的解决方案都不适合我 我需要向响应头isAuth添加特殊属性,该属性必须为true。我试着使用set、setHeader、append等。但所有这些方法对我都不起作用 我的中间件: export const isAuthenticated = async (req, res, next) => { res.set('isAuth', true); next(); } 我的控制器,我想在其中读取此标头属性isAuth: impo
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)
};
从“http状态”导入httpStatus;
从“express”导入{RequestHandler};
export-const-controller:RequestHandler=async(请求:请求,回复:响应)=>{
const isAuth=res.header('isAuth');
log('isAuth:',isAuth)
};
在控制器isAuth中,变量不是true,它等于
<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' ]
}
}
ServerResponse{
_事件:[对象:空原型]{
完成:[[函数:绑定重新配置],[函数:OneEvent]],
结束:[函数:onevent]
},
_事件提示:2,
_maxListeners:未定义,
输出数据:[],
输出大小:0,
可写:对,
销毁:错误,
_最后:错,
错误:错误,
真的,
_defaultKeepAlive:对,
useChunkedEncodingByDefault:true,
发送日期:对,
_removedConnection:false,
_removedContLen:错误,
_removedTE:错,
_contentLength:null,
_哈斯博迪:是的,
_预告片:'',
完成:假,
_海德森:错,
插座:插座{
连接:错,
_haderro:false,
_父项:null,
_主机:空,
_readableState:readableState{
objectMode:false,
高水印:16384,
buffer:BufferList{head:null,tail:null,length:0},
长度:0,
管道:[],
是的,
结束:错,
提交:错误,
阅读:没错,
同步:假,
对,,
错误:错误,
可读性听力:错误,
resumeScheduled:false,
错误:错误,
关闭:错误,
自动销毁:错误,
销毁:错误,
错误:空,
关闭:错误,
答案:错,
defaultEncoding:'utf8',
DrainWriters:空,
多目标:错误,
阅读更多:错误,
解码器:空,
编码:空,
[符号(kPaused)]:false
},
_事件:[对象:空原型]{
结束:[数组],
超时:[函数:socketOnTimeout],
数据:[函数:绑定socketOnData],
错误:[数组],
关闭:[数组],
drain:[函数:绑定socketOnDrain],
resume:[功能:OnStocketResume],
暂停:[功能:onSocketPause]
},
_活动日期:8,
_maxListeners:未定义,
_writableState:writableState{
objectMode:false,
高水印:16384,
最终结论:错误,
李安:错,
结尾:错,
结束:错,
完成:假,
销毁:错误,
解码字符串:false,
defaultEncoding:'utf8',
长度:0,
写作:错,
软木塞:0,
是的,
缓冲处理:false,
onwrite:[函数:绑定onwrite],
writeb:null,
writelen:0,
AfterWritecKinfo:null,
缓冲:[],
缓冲索引:0,
是的,
是的,
待定CB:0,
预完成:false,
错误:错误,
关闭:错误,
自动销毁:错误,
错误:空,
关闭:错误,
错误:错误
},
AllowAlfOpen:是的,
_sockname:null,
_pendingData:null,
_彭丁编码:'',
服务器:服务器{
maxHeaderSize:未定义,
不安全的HttpParser:未定义,
_事件:[对象:空原型],
_事件提示:2,
_maxListeners:未定义,
_联系:1,
_句柄:[TCP],
_使用工人:错误,
_工人:[],
_unref:错,
AllowAlfOpen:是的,
pauseOnConnect:false,
HttpAllowWhalfOpen:错误,
超时:0,
keepAliveTimeout:5000,
maxHeadersCount:null,
校长人数:60000,
请求超时:0,
_connectionKey:'6:::3000',
[符号(输入消息)]:[功能:输入消息],
[符号(服务器响应)]:[功能:服务器响应],
[符号(kCapture)]:假,
[符号(异步\u id\u符号)]:189
},
_服务器:服务器{
maxHeaderSize:未定义,
不安全的HttpParser:未定义,
_事件:[对象:空原型],
_事件提示:2,
_maxListeners:未定义,
_联系:1,
_句柄:[TCP],
_使用工人:错误,
_工人:[],
_unref:错,
AllowAlfOpen:是的,
pauseOnConnect:false,
HttpAllowWhalfOpen:错误,
超时:0,
keepAliveTimeout:5000,
maxHeadersCount:null,
校长人数:60000,
请求超时:0,
_connectionKey:'6:::3000',
[符号(输入消息)]:[功能:输入消息],
[符号(服务器响应)]:[功能:服务器响应],
[符号(kCapture)]:假,
[符号(异步\u id\u符号)]:189
},
解析器:HTTPParser{
“0”:[函数:绑定的setRequestTimeout],
“1”:[函数:parserOnHeaders],
“2”:[函数:parserOnHeadersComplete],
“3”:[函数:parserOnBody],
“4”:[函数:parserOnMessageComplete],
“5”:[函数:绑定到ParseRexecute],
“6”:[函数:绑定到ParserTimeout],
_标题:[],
_url:“”,
插座:[圆形*1],
传入:[输入消息],
传出:空,
maxHeaderPairs:2000,
_对,,
onIncoming:[函数:绑定的parserOnIncoming],
[符号(资源\符号)]:[HTTPServerAsyncResource]
},
on:[函数:socketListenerWrap],
addListener:[函数:socketListenerWrap],
prependListener:[函数:socketListenerWrap],
_暂停:错,
_httpMessage:[循环*2],
_对等名称:{地址:'::1',系列:'IPv6',端口:59763},
[符号(异步\u id\u符号)]:238,
[符号(坎德尔)]:TCP{
雷迪