ExpressJS Flashcards
(19 cards)
Create simple express app (without routes) that will listen on port 7777
import express from 'express'; const app = express(); app.listen(7777, () => { console.log( `Express started on http://localhost:${port}` + "; press Ctrl-C to terminate." ); });
What is a middleware
Functions called before handling each request
In what order middlewares are executed
Middleware is executed in what’s known as a pipeline - functions that are loaded first are also executed first.
How to use a middlware (e.g. from a library).
app.use(foo)
How to parse JSON body
app.use(express.json())
What are middleware function signatures
function (err, req, res, next)
- Error middleware
function(req, res, next)
- Regular middleware
How to handle different requests (POST, PUT, DELETE) on /
app.post('/', (req, res) = {}); app.put('/', (req, res) = {}); app.delete('/', (req, res) = {});
How to access name
field in JSON passed to an endpoint.
req.body.name;
How to access parameter q
passed in URL (example For "GET /search?q=tobi+ferret" => "tobi ferret"
req.query.q;
Send JSON response from endpoint
res.json();
Send any response from endpoint with status code 500
res.status(500).send();
Redirect to another endpoint
res.redirect();
Set header in endpoint response
res.set("Content-Type", "text/html");
Routing - Handle routes starting with '/api/members'
with router in './routes/api/members.js'
module. How to define a router
```javascript
app.use(“/api/members”, require(“./routes/api/members”));
const router = express.Router();
// Handle ‘/api/members’
router.get(“/”, (req, res) => {});
export router;
~~~
How cookies work? What headers are used?
- When the server wants the client to store a cookie, it sends a header called
Set-Cookie
containing name/value pairs. - When a client sends a request to a server for which it has cookies, it sends multiple
Cookie
request headers containing the value of the cookies.
List cookie options (at least the most important ones)
domain
- Allows you to assign cookies to specific subdomains.
- Note that you cannot set a cookie for a different domain than the server is running on.
path
- Controls the path this cookie applies to.
- If you use a path of
/
(the default), it will apply to all pages on your site. If you use a path of/foo
, it will apply to the paths/foo
,/foo/bar
, etc.
maxAge
- How long the client should keep the cookie before deleting it, in milliseconds
- If you omit this, the cookie will be deleted when you close your browser.
secure
- Specifies that this cookie will be sent only over a secure (HTTPS) connection.
httpOnly
- Setting this to true specifies the cookie will be modified only by the server (frontend JS cannot modify it)
- This helps prevent XSS attacks.
signed
- Setting this to true signs this cookie, making it available in
res.signedCookies
instead ofres.cookies
- Signed cookies that have been tampered with will be rejected by the server, and the cookie will be moved from
res.signedCookies
tores.cookies
How sessions work
- To implement sessions, something has to be stored on the client.
- The usual method of doing this is a cookie that contains a unique identifier (SID).
- Other way to maintain state in the past was decorating URLs with session information - but this is way obsolete now.
- HTML5 provides another option for sessions called local storage, which offers an advantage over cookies if you need to store larger amounts of data.
How to protect express app against CSRF attacks?
-
Always check content type
application/json
in REST API. - Or, use only GET (no side-effect on the server), and replace POST with PUT, PATCH, DELETE (so it’s covered with CORS).
- Use
csurf
that provides CSRF Token support.
How to configure CORS for an app?
- Allow all
- Allow single domain
const cors = require("cors"); // Allow all requests (i.e. public API) app.use( cors({ origin: "*", }) ); // it's same as app.use(cors()); app.use( cors({ origin: "domain-b.com", }) );