Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions App-2-middleware/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/node_modules
46 changes: 46 additions & 0 deletions App-2-middleware/backend/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import express from "express";
import cors from "cors";

const app = express();

app.use(express.json());
app.use(cors());

function authenticationCheck(req, res, next) {

Choose a reason for hiding this comment

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

Naming is hard. I would suggest that this isn't an authenticationCheck because it doesn't do anything different if the header isn't there. With a name with check in it I'd expect a 401 response if there isn't the required header

const username = req.header("X-Username");

req.username = username ? username : null;

Choose a reason for hiding this comment

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

This code works, but it would probably be more normal to see it written as either

req.username = username ?? null;

or

req.username = username || null;

A useful exercise would be to understand the difference between these two forms (and why the first one is better)

next();
}

function bodyMessageCheck(req, res, next) {
let body = req.body;

if (!Array.isArray(body) || !body.every((item) => typeof item === "string")) {
return res.status(400).json({ error: "Body must be array strings." });
}
req.bodyArray = body;
next();
}

app.use(authenticationCheck);

app.post("/submit", bodyMessageCheck, (req, res) => {
const countArraySubjects = req.bodyArray.length;
const arraySubjects = req.bodyArray.join(", ");

const authMessage = req.username
? `You are authenticated as: ${req.username}`
: `You are not authenticated`;

const bodyMessage =
countArraySubjects === 0
? `You have requested information about 0 subjects.`
: countArraySubjects === 1
? `You have requested information about 1 subject: ${arraySubjects}.`
: `You have requested information about ${countArraySubjects} subjects: ${arraySubjects}.`;

res.send(`${authMessage}\n\n${bodyMessage}`);
});

app.listen(3000, () => console.log("Server running on http://localhost:3000"));
Loading