Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix "res.writeHead is not a function" in Express/node middleware #7708

Merged
merged 6 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/olive-knives-rush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/node': patch
---

fix issuse #7590 "res.writeHead is not a function" in Express/Node middleware
26 changes: 18 additions & 8 deletions packages/integrations/node/src/nodeMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
import type { NodeApp } from 'astro/app/node';
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { ServerResponse } from 'node:http';
import type { Readable } from 'stream';
import { createOutgoingHttpHeaders } from './createOutgoingHttpHeaders';
import { responseIterator } from './response-iterator';
import type { Options } from './types';
import type { ErrorHandlerParams, Options, RequestHandlerParams } from './types';

export default function (app: NodeApp, mode: Options['mode']) {
natemoo-re marked this conversation as resolved.
Show resolved Hide resolved
return async function (
req: IncomingMessage,
res: ServerResponse,
next?: (err?: unknown) => void,
locals?: object
) {
return async function (...args: RequestHandlerParams | ErrorHandlerParams) {
let error = null;
let [req, res, next, locals] = args as RequestHandlerParams;

if (args[0] instanceof Error) {
[error, req, res, next, locals] = args as ErrorHandlerParams;

if (error) {
if (next) {
return next(error);
} else {
throw error;
}
}
}

try {
const route =
mode === 'standalone' ? app.match(req, { matchNotFound: true }) : app.match(req);
Expand Down
11 changes: 11 additions & 0 deletions packages/integrations/node/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { IncomingMessage, ServerResponse } from 'node:http';

export interface UserOptions {
/**
* Specifies the mode that the adapter builds to.
Expand All @@ -14,3 +16,12 @@ export interface Options extends UserOptions {
server: string;
client: string;
}

export type RequestHandlerParams = [
req: IncomingMessage,
res: ServerResponse,
next?: (err?: unknown) => void,
locals?: object
];

export type ErrorHandlerParams = [unknown, ...RequestHandlerParams];