webapp: respond appropriately to each http request method

Fix incorrect responses, like sending content to OPTIONS requests, by implementing the following scheme:

GET
- Respond with the requested resource; static asset, boilerplate etc.

HEAD
- Return headers identical to GET request
- Do not send content (Node.js will automatically skip response content)

OPTIONS
- Respond with 200
- Send an Allow Header listing acceptable request methods
- Do not send content

CONNECT, DELETE, PATCH, POST, PUT, TRACE, etc.
- Respond with 405 Method Not Allowed
- Send an Allow Header listing acceptable request methods
- Do not send content
This commit is contained in:
Nathan Muir
2020-10-28 11:08:06 +13:00
parent 2996ffd499
commit 6644fcdf95

View File

@@ -426,10 +426,6 @@ WebAppInternals.staticFilesMiddleware = async function (
res,
next,
) {
if ('GET' != req.method && 'HEAD' != req.method && 'OPTIONS' != req.method) {
next();
return;
}
var pathname = parseRequest(req).pathname;
try {
pathname = decodeURIComponent(pathname);
@@ -439,11 +435,21 @@ WebAppInternals.staticFilesMiddleware = async function (
}
var serveStaticJs = function (s) {
res.writeHead(200, {
'Content-type': 'application/javascript; charset=UTF-8'
});
res.write(s);
res.end();
if (req.method === 'GET' || req.method === 'HEAD') {
res.writeHead(200, {
'Content-type': 'application/javascript; charset=UTF-8',
'Content-Length': Buffer.byteLength(s),
});
res.write(s);
res.end();
} else {
const status = req.method === 'OPTIONS' ? 200 : 405;
res.writeHead(status, {
'Allow': 'OPTIONS, GET, HEAD',
'Content-Length': '0',
});
res.end();
}
};
if (_.has(additionalStaticJs, pathname) &&
@@ -476,6 +482,16 @@ WebAppInternals.staticFilesMiddleware = async function (
next();
return;
}
// "send" will handle HEAD & GET requests
if (req.method !== 'HEAD' && req.method !== 'GET') {
const status = req.method === 'OPTIONS' ? 200 : 405;
res.writeHead(status, {
'Allow': 'OPTIONS, GET, HEAD',
'Content-Length': '0',
})
res.end();
return;
}
// We don't need to call pause because, unlike 'static', once we call into
// 'send' and yield to the event loop, we never call another handler with
@@ -522,6 +538,7 @@ WebAppInternals.staticFilesMiddleware = async function (
}
if (info.content) {
res.setHeader('Content-Length', Buffer.byteLength(info.content));
res.write(info.content);
res.end();
} else {
@@ -961,6 +978,13 @@ function runWebAppServer() {
if (! appUrl(req.url)) {
return next();
} else if (req.method !== 'HEAD' && req.method !== 'GET') {
const status = req.method === 'OPTIONS' ? 200 : 405;
res.writeHead(status, {
'Allow': 'OPTIONS, GET, HEAD',
'Content-Length': '0',
})
res.end();
} else {
var headers = {
'Content-Type': 'text/html; charset=utf-8'