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?
Set-Cookie containing name/value pairs.Cookie request headers containing the value of the cookies.List cookie options (at least the most important ones)
domain
path
/ (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
secure
httpOnly
signed
res.signedCookies instead of res.cookiesres.signedCookies to res.cookiesHow sessions work
How to protect express app against CSRF attacks?
application/json in REST API.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",
})
);