http#IncomingMessage TypeScript Examples
The following examples show how to use
http#IncomingMessage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts From farrow with MIT License | 7 votes |
getBody = (req: IncomingMessage, options?: BodyOptions) => {
const type = typeis(req, jsonTypes) || typeis(req, formTypes) || typeis(req, textTypes)
if (type) {
return parseBody(req, options)
}
return null
}
Example #2
Source File: impl.ts From kassette with MIT License | 6 votes |
constructor(
public readonly request: IncomingMessage,
public mode: ProxyConnectMode,
private _intercept: (socket: Socket) => void,
) {
this.connectionsStack = getSocketConnections(this.socket).slice(0);
const parsed = parseHost(request.url!);
if (!parsed) {
this.mode = 'close';
} else {
this.destinationHostname = this.hostname = parsed.hostname;
this.destinationPort = this.port = parsed.port;
}
}
Example #3
Source File: graphql-server.ts From graphql-eslint with MIT License | 6 votes |
private async router(req: IncomingMessage, res: ServerResponse): Promise<void> {
const { pathname } = new URL(req.url, this.base);
if (pathname === '/') {
const { query } = await this.parseData(req);
if (query.includes('query IntrospectionQuery')) {
res.end(JSON.stringify({
data: introspectionQueryResult
}));
}
} else if (pathname === '/my-headers') {
res.end(JSON.stringify(req.headers));
}
}
Example #4
Source File: router.ts From discord-statuspage-v2 with MIT License | 6 votes |
router = {
checkRoute (url: string, _req: IncomingMessage, res: ServerResponse) {
switch (url) {
case ('/'): {
readFile('build/web/pages/index.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/authorized'): {
readFile('build/web/pages/authorized.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/login'): {
readFile('build/web/pages/login.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
case ('/error'): {
readFile('build/web/pages/error.html', (err: Error, data: Buffer) => {
if (err) throw err
res.end(data)
})
break
}
default: {
res.end('An error occurred.')
}
}
}
}
Example #5
Source File: cacheManager.ts From Cromwell with MIT License | 6 votes |
checkAuth = (req: IncomingMessage, authSettings: TAuthSettings) => {
const authHeader = String(req?.headers?.['authorization'] ?? '');
if (authHeader.startsWith('Service ')) {
// Access by secret token from other services such as Renderer
const serviceSecret = authHeader.substring(8, authHeader.length);
if (serviceSecret === authSettings.serviceSecret) {
return true;
}
}
return false;
}
Example #6
Source File: ntrip.ts From caster with GNU General Public License v3.0 | 6 votes |
class NtripCasterRequest extends IncomingMessage {
protocol!: string;
remote?: {
host: string;
port: number;
family: string;
};
mountpoint: string | null = null;
ntripVersion: NtripVersion | null = null;
ntripAgent: boolean = false;
ntripGga?: string;
ntripStr?: string;
agent?: string;
authRequest?: AuthRequest;
authResponse?: AuthResponse;
query?: UrlWithParsedQuery;
rtspTransportParams?: string[];
rtpRemotePort?: number;
rtpSocket?: dgram.Socket;
rtpSession?: RtpSessionInfo;
}
Example #7
Source File: request-handler.helper.ts From node-twitter-api-v2 with Apache License 2.0 | 6 votes |
/* Response helpers */
protected getResponseDataStream(res: IncomingMessage) {
if (this.isCompressionDisabled()) {
return res;
}
const contentEncoding = (res.headers['content-encoding'] || 'identity').trim().toLowerCase();
if (contentEncoding === 'br') {
const brotli = zlib.createBrotliDecompress({
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
});
res.pipe(brotli);
return brotli;
}
if (contentEncoding === 'gzip') {
const gunzip = zlib.createGunzip({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH,
});
res.pipe(gunzip);
return gunzip;
}
if (contentEncoding === 'deflate') {
const inflate = zlib.createInflate({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH,
});
res.pipe(inflate);
return inflate;
}
return res;
}
Example #8
Source File: app.ts From The-TypeScript-Workshop with MIT License | 6 votes |
requestHandler = (req: IncomingMessage, res: ServerResponse) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'DELETE, GET, OPTIONS, POST, PUT'
);
if (req.method === 'OPTIONS') {
return res.end();
}
const urlParts = req.url?.split('/') ?? '/';
switch (urlParts[1]) {
case 'promise':
return promiseRouter(req, res);
default:
return this.handleError(res, 404, 'Not Found.');
}
};
Example #9
Source File: moomoo.ts From sanctuary with Do What The F*ck You Want To Public License | 6 votes |
/**
* Starts a MooMoo.io/Sanctuary server on an existing ws.Server
* @param server the ws.Server to use
*/
export function startServer(server: WSServer) {
let game = new Game();
server.addListener("connection", (socket: WebSocket, req: IncomingMessage) => {
let ip = "";
if (process.env.BEHIND_PROXY) {
ip = (req.headers['x-forwarded-for'] as string).split(/\s*,\s*/)[0];
} else if (req.socket.remoteAddress) {
ip = req.socket.remoteAddress;
}
game.addClient(getID(game), socket, ip);
});
}
Example #10
Source File: Logic.ts From ADR-Gateway with MIT License | 6 votes |
async verify(req: IncomingMessage, logger: winston.Logger): Promise<string> {
try {
let thumbprint = req.headers[this.thumbprintHeader];
if (typeof thumbprint != 'string') {
throw new Error("Expected exactly one client certificate thumbprint header: "+this.thumbprintHeader);
}
return thumbprint;
} catch (err) {
logger.error("",err);
throw new Error("Client certificate could not be verified");
}
}
Example #11
Source File: UniversalCookiesManager.ts From next-right-now-admin with MIT License | 6 votes |
/**
* Universal Cookie Manager constructor
*
* @param {IncomingMessage} req
* @param {ServerResponse} res
* @param {Cookies} readonlyCookies - Useful if req/res aren't accessible (CSR, or SSR outside of _app), will allow to read cookie (but won't allow writes)
*/
constructor(req?: IncomingMessage, res?: ServerResponse, readonlyCookies?: Cookies) {
this.req = req || null;
this.res = res || null;
this.readonlyCookies = readonlyCookies || null;
}
Example #12
Source File: ExpressPlugin.ts From skywalking-nodejs with Apache License 2.0 | 6 votes |
private interceptServerRequest(installer: PluginInstaller) {
const router = installer.require('express/lib/router');
const _handle = router.handle;
router.handle = function (req: IncomingMessage, res: ServerResponse, next: any) {
const carrier = ContextCarrier.from((req as any).headers || {});
const operation = (req.url || '/').replace(/\?.*/g, '');
const span = ignoreHttpMethodCheck(req.method ?? 'GET')
? DummySpan.create()
: ContextManager.current.newEntrySpan(operation, carrier, Component.HTTP_SERVER);
span.component = Component.EXPRESS;
if (span.depth)
// if we inherited from http then just change component ID and let http do the work
return _handle.apply(this, arguments);
return HttpPlugin.wrapHttpResponse(span, req, res, () => {
// http plugin disabled, we use its mechanism anyway
try {
return _handle.call(this, req, res, (err: Error) => {
span.error(err);
next.call(this, err);
});
} finally {
// req.protocol is only possibly available after call to _handle()
span.tag(
Tag.httpURL(
((req as any).protocol ? (req as any).protocol + '://' : '') + (req.headers.host || '') + req.url,
),
);
}
});
};
}
Example #13
Source File: index.ts From banners with MIT License | 6 votes |
export default async function handler(req: IncomingMessage, res: ServerResponse) {
try {
const parsedReq = parseRequest(req);
const html = getHtml(parsedReq);
if (isHtmlDebug) {
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}
const { fileType } = parsedReq;
const file = await getScreenshot(html, fileType, isDev);
res.statusCode = 200;
res.setHeader('Content-Type', `image/${fileType}`);
res.setHeader('Cache-Control', `public, immutable, no-transform, s-maxage=31536000, max-age=31536000`);
res.end(file);
} catch (e) {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Internal Error</h1><p>Sorry, there was a problem</p>');
console.error(e);
}
}
Example #14
Source File: oauthClientServer.spec.ts From cli with Apache License 2.0 | 6 votes |
mockedCreateServer.mockImplementation((listener?: RequestListener) => {
const req = {
url: '/?code=TheCode&state=TheState',
} as unknown as IncomingMessage;
const res = {end: jest.fn()} as unknown as ServerResponse;
process.nextTick(() => listener && listener(req, res));
return {
listen: mockedServerListen,
close: mockedServerClose,
} as unknown as Server;
});
Example #15
Source File: auth.ts From hakka with MIT License | 6 votes |
getServerSession = async (
req: NextApiRequest | IncomingMessage,
): Promise<{ user: AuthUser | null }> => {
const token = cookie.parse(req.headers.cookie || '')[AUTH_COOKIE_NAME]
const cookieUserPayload = await parseSecureToken(token)
if (!cookieUserPayload) {
return { user: null }
}
const user = await prisma.user.findUnique({
where: {
id: cookieUserPayload.userId,
},
})
return {
user: user
? {
id: user.id,
username: user.username,
avatar: user.avatar,
isAdmin: isAdmin({ id: user.id }),
createdAt: user.createdAt.getTime(),
}
: null,
}
}
Example #16
Source File: index.ts From farrow with MIT License | 6 votes |
cors = (
options?: CorsOptions | CorsOptionsDelegate<IncomingMessage>,
): Middleware<any, MaybeAsyncResponse> => {
const cors = promisify(
Cors(
typeof options === 'function'
? options
: {
...options,
preflightContinue: true,
},
),
)
return async (request, next) => {
const req = useReq()
const res = useRes()
try {
await cors(req, res)
if (req.method?.toLowerCase() === 'options') {
if (typeof options === 'object') {
if (options.preflightContinue) {
return next(request)
}
}
return Response.status(204).string('')
}
return next(request)
} catch (error: any) {
return Response.status(500).text(error.message)
}
}
}
Example #17
Source File: multipleRangeDownloader.ts From electron-differential-updater with MIT License | 6 votes |
export function checkIsRangesSupported(response: IncomingMessage, reject: (error: Error) => void): boolean {
// Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.
if (response.statusCode!! >= 400) {
reject(createHttpError(response))
return false
}
if (response.statusCode !== 206) {
const acceptRanges = safeGetHeader(response, "accept-ranges")
if (acceptRanges == null || acceptRanges === "none") {
reject(new Error(`Server doesn't support Accept-Ranges (response code ${response.statusCode})`))
return false
}
}
return true
}
Example #18
Source File: server.ts From cardano-rosetta with Apache License 2.0 | 6 votes |
buildServer = (
services: Services,
cardanoCli: CardanoCli,
cardanoNode: CardanoNode,
logLevel: string,
extraParameters: ExtraParams
): fastify.FastifyInstance<Server, IncomingMessage, ServerResponse> => {
const server = fastify({ logger: { level: logLevel }, bodyLimit: getBodyLimit() });
const { networkId, pageSize, mock, disableSearchApi } = extraParameters;
if (!mock) server.register(metricsPlugin, { endpoint: '/metrics' });
server.register(fastifyBlipp);
server.register(openapiGlue, {
specification: `${__dirname}/openApi.json`,
service: Controllers.configure(services, cardanoCli, cardanoNode, pageSize, disableSearchApi),
noAdditional: true
});
// Custom error handling is needed as the specified by Rosetta API doesn't match
// the fastify default one
server.setErrorHandler((error: Error, request, reply) => {
let toSend = error;
request.log.error(error, '[errorHandler] An error ocurred and will be sent as response');
if (error instanceof ApiError === false) {
toSend = ErrorFactory.unspecifiedError(`An error occurred for request ${request.id}: ${error.message}`);
}
// rosseta-go-sdk always returns 500
reply.status(StatusCodes.INTERNAL_SERVER_ERROR).send({ ...toSend, message: toSend.message });
});
return server;
}
Example #19
Source File: checkBasicAuth.ts From nextjs-basic-auth with MIT License | 6 votes |
async function checkBasicAuth(
req: IncomingMessage,
res: ServerResponse,
users: User[]
) {
if (!req.headers.authorization) {
res.setHeader("WWW-Authenticate", 'Basic realm="Protected"')
res.statusCode = 401
res.end("Unauthorized")
} else {
const [user, password] = authHeaderToBase64(req.headers.authorization)
if (!findAndCheckUser(user, password, users)) {
res.setHeader("WWW-Authenticate", 'Basic realm="Protected"')
res.statusCode = 401
}
}
}
Example #20
Source File: Csrf.ts From core with GNU Affero General Public License v3.0 | 6 votes |
getToken = (req: IncomingMessage, res: ServerResponse) => {
const parsed = parse(req.headers.cookie || '')
let key: string = parsed[csrfKey]
if (!key || !tokenVerify(key)) {
key = tokenCreate()
res.setHeader(
'set-cookie',
serialize(csrfKey, key, {
httpOnly: true,
sameSite: 'lax',
path: '/'
})
)
}
return key
}
Example #21
Source File: HTTPError.ts From dis.ts with MIT License | 6 votes |
constructor(request: ClientRequest, response: IncomingMessage, payload: Record<string | number, unknown>, stack: string, meta: HTTPResponse) {
super(`${response.statusCode} - ${response.statusMessage}`);
Object.defineProperty(this, 'request', {
enumerable: false,
value: request,
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: response,
});
Object.defineProperty(this, 'statusCode', {
enumerable: false,
value: response.statusCode,
});
Object.defineProperty(this, 'payload', {
enumerable: false,
value: payload,
});
Object.defineProperty(this, 'meta', {
enumerable: false,
value: meta,
});
this.stack = `${this.name}: ${this.message}\n${stack}`;
}
Example #22
Source File: mock-server.ts From amman with Apache License 2.0 | 6 votes |
function handleUpload(
req: IncomingMessage,
res: ServerResponse,
resource: string
) {
const contentLength = parseInt(req.headers?.['content-length'] ?? '')
if (isNaN(contentLength) || contentLength <= 0) {
return fail(res, 'Missing File to Upload', 411)
}
logTrace(`uploading ${contentLength} bytes to ${resource}`)
const dstStream = fs.createWriteStream(resource)
let failed = false
dstStream.on('error', (error) => {
logError(error)
failed = true
fail(res, 'Upload failed', 500)
})
req.pipe(dstStream)
req.on('end', () => {
dstStream.close(() => {
if (!failed) {
writeStatusHead(res, 200)
res.end()
}
})
})
}
Example #23
Source File: server.ts From cross-seed with Apache License 2.0 | 6 votes |
async function handleRequest(
req: IncomingMessage,
res: ServerResponse
): Promise<void> {
if (req.method !== "POST") {
res.writeHead(405);
res.end("Methods allowed: POST");
return;
}
switch (req.url) {
case "/api/webhook": {
logger.verbose({
label: Label.SERVER,
message: "POST /api/webhook",
});
return search(req, res);
}
case "/api/announce": {
logger.verbose({
label: Label.SERVER,
message: "POST /api/announce",
});
return announce(req, res);
}
default: {
res.writeHead(404);
res.end("Endpoint not found");
return;
}
}
}
Example #24
Source File: createServer.ts From web with MIT License | 6 votes |
/**
* A request handler that returns a 301 HTTP Redirect to the same location as the original
* request but using the https protocol
*/
function httpsRedirect(req: IncomingMessage, res: ServerResponse) {
const { host } = req.headers;
res.writeHead(301, { Location: `https://${host}${req.url}` });
res.end();
}
Example #25
Source File: tracing.axios-interceptor.ts From nest-xray with MIT License | 6 votes |
public responseRejected(): AxiosRejectedInterceptor {
// Non 2xx Status Code
// Add error to Subsegment
// Close Subsegment
return (error) => {
if (this.isAxiosError(error)) {
try {
const subSegment = this.getSubSegmentFromConfig(error.config);
if (subSegment) {
if (error.request && error.response) {
const request = error.request as ClientRequest;
const response = {
statusCode: error.response.status,
} as IncomingMessage;
subSegment.addRemoteRequestData(request, response, true);
} else if (error.config) {
// Networking Error
// TODO: Implement addRemoteRequestData
}
subSegment.close(error);
}
} catch (tracingError) {
// response error is "more important" than the error from tracing
// so we swallow the tracing exception (probably TracingNotInitializedException)
}
}
throw error;
};
}
Example #26
Source File: provide-location.ts From universal with MIT License | 6 votes |
export function provideLocation(req: IncomingMessage): ValueProvider {
const protocol = 'encrypted' in req.socket ? 'https' : 'http';
const url: any = new URL(`${protocol}://${req.headers['host']}${req.url}`);
url.assign = emptyFunction;
url.reload = emptyFunction;
url.replace = emptyFunction;
url.ancestorOrigins = new (class extends Array<string> implements DOMStringList {
contains(): boolean {
return false;
}
item(): null {
return null;
}
})();
return {
provide: SSR_LOCATION,
useValue: url,
};
}
Example #27
Source File: http-request.ts From shadowsocks-electron with GNU General Public License v3.0 | 6 votes |
export function get(url: string, headers?: { [key: string]: string }): Promise<jsonResult> {
const isHttps = /^(https:\/\/)/.test(url);
const httpLib = isHttps ? https : http;
return new Promise((resolve, reject) => {
const req = httpLib.get(url, (res: IncomingMessage) => {
let data : any = '';
res.on('data', (chunk: string) => {
data += chunk || '';
});
res.on('end', () => {
try {
data = JSON.parse(data);
} catch (error) {
data = {
error: null,
result: data
}
} finally {
resolve({
error: null,
data,
});
}
});
});
req.on('error', (err: Error) => {
resolve({
error: err,
data: null,
});
});
});
}
Example #28
Source File: context.ts From server with Apache License 2.0 | 6 votes |
public static create = async (req: IncomingMessage) => {
const ctx = new Context()
let token = req.headers['x-token']?.toString();
if (!token) {
const idx = req.url?.indexOf('token=')
if (idx && idx !== -1) token = req.url?.substr(idx + 6)
}
if (token) {
try {
const res = await jwt.verify(token, <string>process.env.SECRET);
ctx.currentUser = <LoggedUser>res
if (ctx.currentUser.tenantId !== '0') {
const mng = ModelsManager.getInstance().getModelManager(ctx.currentUser.tenantId)
ctx.user = mng?.getUsers().find(user => user.getUser().id === ctx.currentUser!.id)
}
} catch (e) {
throw new jwt.JsonWebTokenError('Your session expired. Sign in again.');
}
}
return ctx
}
Example #29
Source File: OAL.ts From QuestMirror with Apache License 2.0 | 6 votes |
// httpsリクエストを投げる
private requestHttps(url: string, savePath: string, callback: Function): void {
let request = https.get(url, (res) => {
let resMessage = <IncomingMessage>res
if (resMessage.statusCode == 200) { // ダウンロードするとき
var file = fs.createWriteStream(savePath);
res.on('data', function(chunk){
file.write(chunk);
}).on('end', function(){
file.end();
if (callback) {
callback();
}
});
} else if (resMessage.statusCode == 302) { // リダイレクトするとき
let redirectUrl = <string>res.headers.location
this.requestHttps(redirectUrl, savePath, callback);
}
})
}