-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
53 lines (46 loc) · 1.26 KB
/
middleware.js
File metadata and controls
53 lines (46 loc) · 1.26 KB
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
/**
* Set the CORS headers on the response object
* @param {object} req
* @param {object} res
* @param {function} next
*/
function cors(req, res, next) {
const origin = req.headers.origin
// Set the CORS headers
res.setHeader('Access-Control-Allow-Origin', origin || '*')
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS, XMODIFY')
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Max-Age', '86400')
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept')
next()
}
/**
* Handle errors
* @param {object} err
* @param {object} req
* @param {object} res
* @param {function} next
*/
function handleError(err, req, res, next) {
// Log the error to our server's console
console.error(err)
// If the response has already been sent, we can't send another response
if (res.headersSent) {
return next(err)
}
// Send a 500 error response
res.status(500).json({ error: "Internal Error Occurred" })
}
/**
* Send a 404 response if no route is found
* @param {object} req
* @param {object} res
*/
function notFound(req, res) {
res.status(404).json({ error: "Not Found" })
}
module.exports = {
cors,
handleError,
notFound
}