forked from pouchdb/add-cors-to-couchdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (80 loc) · 1.73 KB
/
index.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
'use strict';
var url = require('url');
var transports = {};
transports.https = require('https');
transports.http = require('http');
module.exports = addCors;
function addCors(inurl, auth, callback) {
if (typeof auth === 'function') {
callback = auth;
auth = void 0;
}
var len = todo.length;
var errored = false;
function cb(err, resp) {
if (errored) {
return;
}
if (err) {
errored = true;
return callback(err);
}
len--;
if (!len) {
callback();
}
}
todo.forEach(function (item) {
var opts = url.parse(inurl + item.path);
if (auth) {
opts.auth = auth;
}
send(opts, item.value, cb);
});
}
function formatProtocol(protocol) {
if (protocol.slice(-1) === ':') {
protocol = protocol.slice(0, -1);
}
return protocol.toLowerCase();
}
function send(opts, data, callback) {
opts.method = 'PUT';
var req = transports[formatProtocol(opts.protocol)].request(opts, function(res) {
var output = '';
if (res.statusCode !== 200) {
callback(new Error('got a ' + res.statusCode + ' code'));
res.on('data', function () {});
return;
}
res.on('data', function (chunk) {
output += chunk.toString();
}).on('error', callback).on('end', function () {
callback(null, output);
});
});
req.write(data);
req.end();
}
var todo = [
{
path: '/_config/httpd/enable_cors',
value: '"true"'
},
{
path: '/_config/cors/origins',
value: '"*"'
},
{
path: '/_config/cors/credentials',
value: '"true"'
},
{
path: '/_config/cors/methods',
value: '"GET, PUT, POST, HEAD, DELETE"'
},
{
path: '/_config/cors/headers',
value: '"accept, authorization, content-type, origin, referer"'
}
];