-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
79 lines (68 loc) · 1.95 KB
/
server.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
const http = require('http');
const express = require('express');
const enforce = require('express-sslify');
const next = require('next');
const bodyParser = require('body-parser');
const request = require('request');
const { body, check, validationResult } = require('express-validator/check');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const handleResponse = (req, res) => {
handle(req, res);
};
const handleError = (err) => {
if (err) throw err;
console.log(`Ready on localhost:${port}`);
};
app.prepare().then(() => {
const expressApp = express();
expressApp.use(bodyParser.urlencoded({ extended: false }));
expressApp.use(bodyParser.json());
if (!dev) {
expressApp.use(enforce.HTTPS({ trustProtoHeader: true }));
console.log('Using enforced https;');
}
expressApp.post('/processForm', [
body('name')
.isLength({ min: 1, max: 100 })
.trim()
.escape(),
body('email')
.isLength({ min: 1, max: 100 })
.isEmail()
.normalizeEmail(),
check('company')
.isLength({ min: 1, max: 100 })
.trim()
.escape(),
check('message')
.isLength({ min: 1, max: 10000 })
.not().isEmpty()
.trim()
.escape(),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
const {
name, email, company, message,
} = req.body;
const form = {
name, email, company, message,
};
request.post({
url: `${process.env.API_URL}/contact`,
form,
}, (error, response, data) => {
if (error != null) {
return res.status(500).send(error);
}
return res.status(response.statusCode).send(data);
});
});
expressApp.use(handleResponse);
http.createServer(expressApp).listen(port, handleError);
});