Repository navigation
Expand file tree
/
Copy pathmiddleware.js
More file actions
82 lines (58 loc) · 2 KB
/
Copy pathmiddleware.js
File metadata and controls
82 lines (58 loc) · 2 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
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
/**
* Middleware to get data from PHP
*/
const getFromPHP = (phpHost, phpPort, phpPath, phpObject) => {
if (typeof phpHost === 'undefined') {
throw new Error('phpHost was not defined');
}
if (typeof phpPort === 'undefined') {
throw new Error('phpPort was not defined');
}
if (typeof phpPath === 'undefined') {
phpPath = '/';
}
if (typeof phpObject !== 'object' ) {
phpObject = {};
}
return (req, res, next) => {
if (typeof req.php === 'undefined') {
req.php = {};
}
const options = {
hostname: phpHost, // change this to your php server host
port: phpPort, // change this with your php server port
path: phpPath, // change this with your php server path to script
method: 'POST',
headers: {
// here we send 'NODE-REQUEST', it will be available in php unde $_SERVER global prefixed with HTTP_ string because is a custom client request header.
'NODE-REQUEST': JSON.stringify(phpObject)
}
};
const isJSON = (str ) => {
try {
let j = JSON.parse(str);
return typeof j === 'object' && j !== null;
} catch (e) {
return false;
}
};
const httpModule = require('http');
let reqHttp = httpModule.request(options, (response) => {
if( typeof response.headers['node-response'] === 'undefined' || !isJSON(response.headers['node-response'])){
req.php = {};
}else{
req.php = JSON.parse(response.headers['node-response']);
}
next();
});
reqHttp.on('error', (e) => {
console.error(`problem with request to php server: ${e.message}`);
next();
});
reqHttp.on('end', () => {
next();
});
reqHttp.end();
}
}
exports.getFromPHP = getFromPHP;