Skip to content

Instantly share code, notes, and snippets.

@cthrash
Last active December 14, 2018 18:01
Show Gist options
  • Save cthrash/22112d78dd006cb04caa27d1d720315a to your computer and use it in GitHub Desktop.
Save cthrash/22112d78dd006cb04caa27d1d720315a to your computer and use it in GitHub Desktop.
Cognitive Service Container Proxy Example
// 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'));
});
@AugustKarlstedt
Copy link

Awesome, thanks @cthrash!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment