-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
69 lines (54 loc) · 1.41 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import bodyParser from 'body-parser';
import express, { NextFunction, Request, Response } from 'express';
const cors = require('cors');
const port = 3000;
const app = express();
const corsOptions = {
origin: [
/localhost(:\d+)?$/,
'https://www.google.com'
],
};
// 1. normal
app.get('/', function (req, res, next) {
res.send(`Hello World normal`);
});
// 2. middleware
app.get('/middleware', (req, res, next) => {
req.params = {
someText: 'hello',
};
next();
}, (req, res) => {
res.send(`modified params ${JSON.stringify(req.params)}`);
});
// 3. create middleware function
const middleWareFunction = (req: Request, res: Response, next: NextFunction) => {
req.params = {
someText: 'hello',
};
next();
};
app.get('/middleware2', middleWareFunction, (req, res) => {
res.send(`modified params ${JSON.stringify(req.params)}`);
});
// 4. cors
app.get('/with-cors', cors(corsOptions), function (req, res, next) {
const { name } = req.query;
res.send('Hello World with cors');
});
app.post('/post-normal', (req, res) => {
console.log(req.body);
res.send('ok');
});
app.post('/post-with-parser', bodyParser.json(), (req, res) => {
console.log(req.body);
res.send('ok');
});
app.post('/post-form-with-parser', bodyParser.urlencoded({ extended: false }), (req, res) => {
console.log(req.body);
res.send('ok');
});
app.listen(port, () => {
console.log(`listening to port ${port}`);
});