Forked from cthrash/CognitiveServiceContainerProxyExample.js
Created
December 14, 2018 18:01
-
-
Save AugustKarlstedt/de96f77461e50d2e31a97230a87744d5 to your computer and use it in GitHub Desktop.
Cognitive Service Container Proxy Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cognitive Service containers don't currently handle Cross-origin resource sharing (CORS) headers. This means that for user agents | |
// that enforce CORS (browsers, typically), requests will fail. The following code is an example of how you might work around this, | |
// temporarily, until the containers are fixed. This code is provided as-is, with no guarantees. | |
// | |
// The following is a modified version of code found here: https://github.com/ccoenraets/cors-proxy. | |
var express = require('express'), | |
request = require('request'), | |
bodyParser = require('body-parser'), | |
app = express(); | |
let ocrBase = 'http://localhost:5000'; // Adjust if necessary | |
app.use(bodyParser.raw({ | |
limit: '4MB', | |
type: '*/*' | |
})); | |
app.all('*', function (req, res, next) { | |
// Set CORS headers: allow all origins, methods, and headers: you may want to lock this down in a production environment | |
res.header("Access-Control-Allow-Origin", "*"); | |
res.header("Access-Control-Allow-Methods", "GET, PUT, PATCH, POST, DELETE"); | |
res.header("Access-Control-Allow-Headers", req.header('access-control-request-headers')); | |
if (req.method === 'OPTIONS') { | |
// CORS Preflight | |
res.send(); | |
} else { | |
new_req = { | |
url: ocrBase + req.url, | |
method: req.method, | |
query: req.query, | |
headers: req.headers, | |
body: req.body | |
}; | |
request(new_req, | |
function (error, response, body) { | |
if (error) { | |
console.error('error: ' + response) | |
} | |
}).pipe(res); | |
} | |
}); | |
app.set('port', process.env.PORT || 3000); | |
app.listen(app.get('port'), function () { | |
console.log('Proxy server listening on port ' + app.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment