Proxies
Overview
A proxy is a web server that forwards calls made to it to another web server. It can be useful for two reasons.
- Enables Cross Origin Requests - some webservers will block cross origin request. (That is, requests from a browser that
is connected to a URL from a different server) These sites still provide access to their data and/or resources using
HTTP, however, you are required to access it through a process running on the local machine. (not the browser)
A proxy is a process running locally that will accept requests from your browser and forward the request, then returning
the result.
- Provides and optional security layer - for users who do not want to save their connection keys to the davinci server
for a particular resource, can use a proxy server which contains the keys. Then all calls to the secure resource
first go through the proxy which adds the necessary connection information.
Proxy Code
The sample proxy server is coded in Javascript. In order to use it, you need to have
node js
installed.
It depends on two depenencies.
The following script installs the two packages.
npm install express
npm install cors
Full Proxy
const express = require('express')
const https = require('https');
const fs = require('fs');
const path = require('path');
const app = express()
const port = 443;
//you need cors, otherwise davinc will report an error
const cors = require('cors');
app.use(cors());
const axios = require('axios');
// Receive new request
// Forward to application server
const handler = async (req, res) =>{
// Destructure following properties from request object
const { method, url, headers, body } = req;
const server = 'https://server.com'
try{
let instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
// Requesting to underlying application server
//console.log('call to '+`${server}${url}`)
const response = await instance({
url: `${server}${url}`,
method: method,
//headers: headers,
//headers:{},
data: body
});
//console.log('response - '+response.data)
// Send back the response data
// from application server to client
res.send(JSON.stringify(response.data));
}
catch(err){
// Send back the error message
//console.log('error - '+err.toString())
res.status(500).send("Server error!")
}
}
// When receive new request
// Pass it to handler method
app.use((req,res)=>{handler(req, res)});
app.listen(port, () => {
console.log(`listening on port `+port.toString());
});
//The following is for using SSL on the proxy. Comment out the app.listen statement above, and uncomment the following.
//Make sure your certificates are located in the cert folder.
/*
let sslServer = https.createServer({
key: fs.readFileSync(path.join(__dirname, 'cert', 'ssl.key')),
cert: fs.readFileSync(path.join(__dirname, 'cert', 'ssl.crt'))
}, app);
sslServer.listen(port, () => {
console.log(`listening on port `+port.toString());
});
*/