http#ServerResponse TypeScript Examples
The following examples show how to use
http#ServerResponse.
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: utilities.ts From now-shopify-auth with MIT License | 7 votes |
export function redirectToAuth(
{
shop,
res,
routes: {
fallbackRoute,
authRoute,
},
}: {
shop?: string;
res?: ServerResponse;
routes: Routes;
},
) {
const routeForRedirect = shop ? `${authRoute}?shop=${shop}` : fallbackRoute;
redirect({ res, location: routeForRedirect });
}
Example #2
Source File: util.ts From farrow with MIT License | 7 votes |
getContentLength = (res: ServerResponse) => {
const contentLength = res.getHeader('Content-Length')
if (typeof contentLength === 'string') {
const length = parseFloat(contentLength)
return isNaN(length) ? 0 : length
}
if (typeof contentLength !== 'number') {
return 0
}
return contentLength
}
Example #3
Source File: index.ts From nextjs-basic-auth with MIT License | 6 votes |
function init(options: Options = {}) {
const { users } = options
if (!users) {
throw new Error(
"You must supply an array of user/password combinations in the config."
)
}
return (req: IncomingMessage, res: ServerResponse) => {
checkBasicAuth(req, res, users)
}
}
Example #4
Source File: redirect.ts From now-shopify-auth with MIT License | 6 votes |
export default function redirect({ res, location }: { res?: ServerResponse, location: string }): void {
if (res) {
res.writeHead(302, { Location: location });
return res.end();
}
if (typeof window !== "undefined") {
document.location.pathname = location;
}
}
Example #5
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 #6
Source File: http.ts From farrow with MIT License | 6 votes |
handleStream = (res: ServerResponse, stream: Stream) => {
return new Promise<void>((resolve, reject) => {
stream.once('error', reject)
stream.pipe(res)
onfinish(res, (error) => {
if (error) {
reject(error)
} else {
resolve()
}
destroy(stream)
})
})
}
Example #7
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 6 votes |
updateCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const id = req.params.id;
const car = req.body;
const { ...updateData } = car;
const update = await Car.findByIdAndUpdate(id, updateData, { new: true });
return update;
} catch (err) {
throw boom.boomify(err);
}
}
Example #8
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 #9
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 #10
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 6 votes |
getSingleCar = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>) => {
try {
const id = req.params.id;
const car = await Car.findById(id);
return car;
} catch (err) {
throw boom.boomify(err);
}
}
Example #11
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 #12
Source File: mock-server.ts From amman with Apache License 2.0 | 6 votes |
// -----------------
// Helpers
// -----------------
function writeStatusHead(res: ServerResponse, status: number) {
res.writeHead(status, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, DELETE, PUT',
'Access-Control-Allow-Headers': '*',
'Access-Control-Max-Age': 2592000, // 30 days
})
}
Example #13
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 #14
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 #15
Source File: dataServer.ts From nextclade with MIT License | 6 votes |
function main() {
const app = express()
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
const newHeaders = modifyHeaders({ request: req, response: res }) as NewHeaders
Object.entries(newHeaders).forEach(([header, arr]) => {
const [{ value }] = arr
if (header.toLowerCase() === 'strict-transport-security') {
return
}
res.set({ [header.toLowerCase()]: value })
})
next()
})
app.use(allowMethods(['GET', 'HEAD']))
app.use(history())
app.get(
'*',
expressStaticGzip(DATA_OUTPUT_DIR, {
enableBrotli: false,
serveStatic: {
setHeaders: (res: ServerResponse) => {
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Max-Age', '3000')
},
},
}),
)
const port = getenv('DATA_LOCAL_PORT')
app.listen(port, () => {
console.info(`Serving ${DATA_OUTPUT_DIR} on http://localhost:${port}`)
})
}
Example #16
Source File: index.tsx From plasmic with MIT License | 6 votes |
async getActiveVariation(opts: {
req?: ServerRequest;
res?: ServerResponse;
known?: Record<string, string>;
traits: Record<string, string | number | boolean>;
}) {
return this._getActiveVariation({
traits: opts.traits,
getKnownValue: (key: string) => {
if (opts.known) {
return opts.known[key];
} else {
return opts.req?.cookies[`plasmic:${key}`] ?? undefined;
}
},
updateKnownValue: (key: string, value: string) => {
if (opts.res) {
const cookie = `plasmic:${key}=${value}`;
const resCookie = opts.res?.getHeader('Set-Cookie') ?? [];
let newCookies: string[] = [];
if (Array.isArray(resCookie)) {
newCookies = [...resCookie, `plasmic:${key}=${value}`];
} else {
newCookies = [`${resCookie}`, cookie];
}
opts.res?.setHeader('Set-Cookie', newCookies);
}
},
});
}
Example #17
Source File: IncomingRequest.ts From ZenTS with MIT License | 6 votes |
public async handle(
factory: RequestFactory,
route: Route,
req: IncomingMessage,
res: ServerResponse,
params: IncomingParams,
requestConfig: RequestConfig,
securityProviders: SecurityProviders,
): Promise<void> {
const context = await this.buildContext(req, res, params, route)
const authentication = await this.authenticate(route.authProvider, context, securityProviders)
if (authentication.isAuth) {
if (requestConfig.type === REQUEST_TYPE.CONTROLLER) {
requestConfig.loadedUser = {
provider: route.authProvider,
user: authentication.user,
sessionId: authentication.sessionId,
}
}
if (context.isValid) {
const handler = factory.build(context, requestConfig, route)
await handler.run()
} else {
context.error.badData('Bad Data', {
errors: context.validationErrors,
})
}
} else if (authentication.securityProvider) {
await authentication.securityProvider.forbidden(context)
} else {
context.error.forbidden()
}
}
Example #18
Source File: server.ts From storage-api with Apache License 2.0 | 6 votes |
(async () => {
const { isMultitenant } = getConfig()
if (isMultitenant) {
await runMultitenantMigrations()
await listenForTenantUpdate()
const adminApp: FastifyInstance<Server, IncomingMessage, ServerResponse> = buildAdmin({
logger,
})
try {
await adminApp.listen(5001, '0.0.0.0')
} catch (err) {
adminApp.log.error(err)
process.exit(1)
}
} else {
await runMigrations()
}
const app: FastifyInstance<Server, IncomingMessage, ServerResponse> = build({
logger,
exposeDocs,
})
app.listen(5000, '0.0.0.0', (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
})()
Example #19
Source File: RequestContext.ts From double-agent with MIT License | 6 votes |
constructor(
public readonly server: BaseServer,
public readonly req: IncomingMessage | http2.Http2ServerRequest,
public readonly res: ServerResponse | http2.Http2ServerResponse,
public readonly url: URL,
public readonly requestDetails: IRequestDetails,
public readonly session: Session,
) {
this.plugin = server.plugin;
const pageIndexStr = url.searchParams.get('pageIndex');
if (pageIndexStr) {
const pages = this.plugin.pagesByAssignmentType[this.session.assignmentType];
const pageIndex = Number(pageIndexStr);
this.currentPageIndex = pageIndex;
this.nextPageIndex = pageIndex + 1;
if (this.nextPageIndex >= pages.length) this.nextPageIndex = undefined;
this.session.trackCurrentPageIndex(this.plugin.id, this.currentPageIndex);
}
}
Example #20
Source File: verify-request.d.ts From flect-chime-sdk-demo with Apache License 2.0 | 6 votes |
/**
* Verify the authenticity of an incoming HTTP request from Slack and buffer the HTTP body.
*
* When verification succeeds, the returned promise is resolved. When verification fails, the returned promise is
* rejected with an error describing the reason. IMPORTANT: The error messages may contain sensitive information about
* failures, do not return the error message text to users in a production environment. It's recommended to catch all
* errors and return an opaque failure (HTTP status code 401, no body).
*
* Verification requires consuming `req` as a Readable stream. If the `req` was consumed before this function is called,
* then this function expects it to be stored as a Buffer at `req.rawBody`. This is a convention used by infrastructure
* platforms such as Google Cloud Platform. When the function returns, the buffered body is stored at the `req.rawBody`
* property for further handling.
*
* The function is designed to be curry-able for use as a standard http RequestListener, and therefore keeps `req` and
* `res` are the last arguments. However, the function is also async, which means when it is curried for use as a
* RequestListener, the caller should also capture and use the return value.
*/
export declare function verify(options: VerifyOptions, req: IncomingMessage, _res?: ServerResponse): Promise<BufferedIncomingMessage>;
Example #21
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 #22
Source File: index.ts From CloudProxy with MIT License | 6 votes |
function successResponse(successMsg: string, extendedProperties: object, res: ServerResponse, startTimestamp: number) {
const endTimestamp = Date.now()
log.info(`Successful response in ${(endTimestamp - startTimestamp) / 1000} s`)
if (successMsg) { log.info(successMsg) }
const response = Object.assign({
status: 'ok',
message: successMsg || '',
startTimestamp,
endTimestamp,
version
}, extendedProperties || {})
res.writeHead(200, {
'Content-Type': 'application/json'
})
res.write(JSON.stringify(response))
res.end()
}
Example #23
Source File: NuxtServer.ts From nest-nuxt-starter with MIT License | 6 votes |
private init(nuxt: Nuxt): Nuxt {
nuxt.hook('render:route', (url: string) => {
log.debug(`path called ${url}`);
});
nuxt.hook('render:errorMiddleware', (app: ConnectServer) =>
app.use(
(
err: Error,
req: IncomingMessage,
res: ServerResponse,
next: NextFunction,
) => {
log.error(err.message, err.stack);
next(err);
},
),
);
return nuxt;
}
Example #24
Source File: ntrip.ts From caster with GNU General Public License v3.0 | 6 votes |
class NtripCasterResponse extends ServerResponse {
statusVersion = 'HTTP/1.1';
// noinspection JSUnusedGlobalSymbols
/**
* Internal method that stores the response header.
* Override to include NTRIP V1 responses such as ICY 200 OK and SOURCETABLE 200 OK.
*
* @param firstLine HTTP response status line
* @param headers HTTP headers
* @private
*/
_storeHeader(firstLine: string, headers: OutgoingHttpHeaders) {
firstLine = this.statusVersion + firstLine.slice(firstLine.indexOf(' '));
// @ts-ignore Call private _storeHeader
super._storeHeader(firstLine, headers);
//console.log(chalk.green(firstLine));
for (let header in headers) {
// @ts-ignore
//console.log(chalk.green(headers[header][0] + ": " + headers[header][1]));
}
}
error(code: number, response?: string) {
this.statusCode = code;
this.statusMessage = STATUS_CODES[code] as string;
this.removeHeader('Connection');
if (response === undefined) {
this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
}
this.end(response);
}
}
Example #25
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 #26
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 #27
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 #28
Source File: router.ts From The-TypeScript-Workshop with MIT License | 6 votes |
promiseRouter = (req: IncomingMessage, res: ServerResponse) => {
const urlParts = req.url?.split('/') ?? '/';
const requestParam = urlParts[2];
res.setHeader('Content-Type', 'application/json');
switch (req.method) {
case 'DELETE':
if (requestParam) {
return handleDelete(Number.parseInt(requestParam), res);
}
case 'GET':
if (requestParam) {
return handleGetOne(Number.parseInt(requestParam), res);
}
return handleGetAll(res);
case 'POST':
return handleCreate(req, res);
case 'PUT':
return handleUpdate(req, res);
default:
app.handleError(res, 404, 'Not Found.');
}
}
Example #29
Source File: __loader__.ts From BotArcAPIs-Memories with MIT License | 6 votes |
handler_request_favicon = async (response: ServerResponse) => {
let _http_body: string = '';
let _http_status: number = 0;
let _http_content_type: string = '';
const file = require('fs');
try {
await file.promises.readFile('./image/favicon.ico')
.then((data: any) => {
_http_status = 200;
_http_body = data;
_http_content_type = 'image/x-icon';
});
} catch (e) {
syslog.e(e.stack);
return handler_request_notfound(response);
}
// send result to client
response.statusCode = _http_status;
response.setHeader('Content-Type', _http_content_type);
response.setHeader('Server', `${BOTARCAPI_VERSTR}`);
response.end(_http_body);
syslog.v(TAG, 'Send response back');
}