Last active
December 14, 2018 18:01
-
-
Save cthrash/22112d78dd006cb04caa27d1d720315a 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')); | |
}); |
Thanks for the feedback. I've updated this gist based on your feedback. It should work if you chose to send the image in the payload, which your example won't do. This may not be important in your use case.
Fixed an error in new_req
construction. Sorry about that!
Updated to handle other content types.
Awesome, thanks @cthrash!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @cthrash!
I was getting some errors around
req.headers['content-type']
since not all requests had content-type headers, but I was able to modify https://github.com/ccoenraets/cors-proxy with the help of this gist, as updated here: https://gist.github.com/AugustKarlstedt/fbe1a29d62f800de6a44a314c80af0ae