Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(proxy): Add proxy support #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Expand Up @@ -93,7 +93,7 @@ serve({
// set custom mime types, usage https://github.com/broofa/mime#mimedefinetypemap-force--false
mimeTypes: {
'application/javascript': ['js_commonjs-proxy']
}
},

// execute function after server has begun listening
onListening: function (server) {
Expand All @@ -102,6 +102,13 @@ serve({
// by using a bound function, we can access options as `this`
const protocol = this.https ? 'https' : 'http'
console.log(`Server listening at ${protocol}://${host}:${address.port}/`)
},

// Set up simple proxy
// this will route all traffic starting with
// `/api` to http://localhost:8181/api
proxy: {
api: 'http://localhost:8181'
}
})
```
Expand Down
53 changes: 50 additions & 3 deletions src/index.js
@@ -1,6 +1,6 @@
import { readFile } from 'fs'
import { createServer as createHttpsServer } from 'https'
import { createServer } from 'http'
import https, { createServer as createHttpsServer } from 'https'
import http, { createServer } from 'http'
import { resolve, posix } from 'path'

import mime from 'mime'
Expand All @@ -20,14 +20,24 @@ function serve (options = { contentBase: '' }) {
options.port = options.port || 10001
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
options.onListening = options.onListening || function noop () { }
options.openPage = options.openPage || ''
options.proxy = options.proxy || {}
mime.default_type = 'text/plain'

if (options.mimeTypes) {
mime.define(options.mimeTypes, true)
}

// Use http or https as needed
const http_s = options.https ? https : http

const proxies = Object.keys(options.proxy).map(proxy => ({
proxy,
destination: options.proxy[proxy],
test: new RegExp(`\/${proxy}`)
}))

const requestListener = (request, response) => {
// Remove querystring
const unsafePath = decodeURI(request.url.split('?')[0])
Expand All @@ -39,6 +49,38 @@ function serve (options = { contentBase: '' }) {
response.setHeader(key, options.headers[key])
})

// Find the appropriate proxy for the request if one exists
const proxy = proxies.find(({ test }) => request.url.match(test))

// If a proxy exists, forward the request to the appropriate server
if (proxy && proxy.destination) {
const { destination } = proxy
const newDestination = `${destination}${request.url}`

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is not well described in the read me how the final destination URL will be compiled.
Also logging the final destination URL before sending the request might help somebody.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm OK with this, but wonder if the logging should be hidden behind a flag?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's entirely fair. Right now the behavior is that your example would work by going to http://httpbin.org/get/api. Is that not the desired behavior? Either way I will add some language to the README to clarify.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, the final url is http://httpbin.org/get/api, but shouldn't this result in 404 status code proxied instead of "Content Encoding Error".
I did not check the actual response cloning code to check what is actually happening.
Maybe I did not test properly.
I also used it to proxy to a complicated apache setup which has reverse proxy and somehow I could not get it working.
Maybe not all request headers from the original request are copied?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I set up the proxy,but always return 404

const { headers, method, statusCode } = request

// Get the request contents
let body = '';
request.on('data', chunk => body += chunk)

// Forward the request
request.on('end', () => {
const proxyRequest = http_s
.request(newDestination, { headers, method }, (proxyResponse) => {
let data = ''
proxyResponse.on('data', chunk => data += chunk)
proxyResponse.on('end', () => {
Object.keys(proxyResponse.headers).forEach(key => response.setHeader(key, proxyResponse.headers[key]))
foundProxy(response, proxyResponse.statusCode, data)
})
})
.end(body, 'utf-8')

proxyRequest.on('error', err => console.error(`There was a problem with the request for ${request.url}: ${err}`))
proxyRequest.end()
})
return
}

readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
Expand Down Expand Up @@ -151,6 +193,11 @@ function found (response, filePath, content) {
response.end(content, 'utf-8')
}

function foundProxy (response, status, content) {
response.writeHead(status)
response.end(content, 'utf-8')
}

function green (text) {
return '\u001b[1m\u001b[32m' + text + '\u001b[39m\u001b[22m'
}
Expand Down