forked from n1k0/readable-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
59 lines (52 loc) · 1.75 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
var scrape = require("./scrape");
var sanitizeResult = require("./sanitize").sanitizeResult;
var express = require("express");
var pkgInfo = require("./package.json");
var app = express();
exports.app = app;
app.use(express.static("static"));
app.use(express.static("node_modules/bootstrap/dist/css"));
/**
* Casts a query string arg into an actual boolean value.
* @param {String} arg The query string arg.
* @return {Boolean}
*/
function boolArg(queryParam) {
if (!queryParam) return false;
return ["1", "on", "true", "yes", "y"].indexOf(queryParam.toLowerCase()) !== -1;
}
app.use(function(req, res, next) {
res.header("Content-Type", "application/json");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, Requested-With, Content-Type, Accept");
next();
});
app.get("/api", function(req, res) {
res.json({
name: pkgInfo.name,
documentation: "https://github.com/n1k0/readable-proxy/blob/master/README.md",
description: pkgInfo.description,
version: pkgInfo.version
});
});
app.get("/api/get", function(req, res) {
var url = req.query.url,
sanitize = boolArg(req.query.sanitize),
userAgent = req.query.userAgent;
if (!url) {
return res.status(400).json({error: "Missing url parameter"});
}
scrape(url, {userAgent: userAgent}).then(function(result) {
res.json(sanitize ? sanitizeResult(result) : result);
}).catch(function(err) {
console.log(err);
res.status(500).json({error: {message: err.message}});
});
});
exports.serve = function() {
var server = app.listen(process.env.PORT || 3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Server listening at http://%s:%s", host, port);
});
};