-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress.js
92 lines (72 loc) · 2.03 KB
/
express.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const express = require('express')
const axios = require('axios');
const timer = require('./middlewares/timer')
const jsontoxml = require ('jsontoxml')
const app = express()
const port = 3000
const host = 'localhost';
//const logStatus = require('./middlewares/logStatus')
app.use(express.urlencoded({extended: false}));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.json());
app.listen(port, host, () => {
console.log(`Example app listening on port ${port}`)
})
const auth = function (req, res, next) {
authorization = req.headers.authorization
if (!auth){
res.status(401);
res.send()
}
else if (auth == 'Bearer 123') res.status(401);
next()
}
app.use(auth)
app.post('/', (req, res, next) => {
console.log("*POST*");
if (req.body.name !== 'avihu') {
next("Bad username");
}
next()
res.status(200).send("good username");
})
app.get('/', (req, res, next) => {
console.log("*GET*");
next()
res.send()
})
app.get('/users', async (req, res, next) => {
usersURL = 'https://jsonplaceholder.typicode.com/users';
responce = await axios.get(usersURL);
data = responce.data;
try {
if (req.query.format === 'xml'){
res.status(200).send(jsontoxml(data));
}
else if (req.query.format === 'json'){
res.status(200).send(jsontoxml(data));
}
response = await axios.get(`${usersURL}/?format=xml&offset=2&limit=2`);
const data = response.data;
xml = jsontoxml(data);
res.status(200).send(xml);
}
catch (err) {
res.status(404).send(err)
}
})
const myLogger = (req, res, next) => {
if (req.method == 'POST') {
console.log(res.statusCode)
}
next()
}
app.use(myLogger)
app.use(timer)
function errorHandler (err, req, res, next) {
if (err === "Bad username") {
res.status(404).send(`Username ${req.body.name} is invalid`);
}
}
app.use(errorHandler)