Skip to content
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/createServer.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,45 @@
/* eslint-disable no-console */
'use strict';

const http = require('http');

function createServer() {
/* Write your code here */
// Return instance of http.Server class
return http.createServer((req, res) => {
const url = new URL(req.url, `http://${req.headers.host}`);
const pathname = url.pathname.slice(1).split('/');
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This method of parsing the pathname does not correctly handle doubled slashes as required. For example, a path like //hello will result in ['', 'hello'] instead of the expected ['hello']. You'll need to filter out the empty strings that result from splitting a path with multiple slashes.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good step forward, but paths with a leading or trailing slash (like / or /users/) still produce an array with empty strings (e.g., [''] or ['users', '']). To meet the requirement of ignoring doubled/trailing/leading slashes, you'll need to filter these empty strings out of the pathname array after splitting the path.


const searchParams = url.searchParams;

if (req.url.includes('..')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Invalid path');

return;
}

if (pathname.includes('//')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');

return;
}

if (pathname.length > 0 || searchParams.size > 0) {
res.writeHead(200, { 'Content-Type': 'application/json' });

res.end(
JSON.stringify({
parts: pathname,
query: Object.fromEntries(searchParams),
}),
);
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});
}

module.exports = {
Expand Down
Loading