Skip to content

Commit

Permalink
Replaces request with express-http-proxy.
Browse files Browse the repository at this point in the history
closes #3344
  • Loading branch information
justinlittman committed Nov 18, 2021
1 parent adecce1 commit 4c61881
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 35 deletions.
52 changes: 52 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"dotenv": "^8.6.0",
"event-stream": "^4.0.1",
"express": "^4.16.4",
"express-http-proxy": "^1.6.3",
"file-saver": "^2.0.5",
"html-webpack-plugin": "^5.3.2",
"identity-obj-proxy": "^3.0.0",
Expand Down
47 changes: 12 additions & 35 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,53 +6,30 @@
*/

import express from "express"
import request from "request"
import Config from "./src/Config"
import _ from "lodash"

import cors from "cors"
import proxy from "express-http-proxy"

const port = 8000
const app = express()

// Required for ElasticSearch proxy middleware to parse response body as JSON
app.use(express.json()) // handle json data
app.use(express.urlencoded({ extended: true })) // handle URL-encoded data

app.use(cors())
app.options("*", cors())

// ElasticSearch proxy middleware
app.post("/api/search/:index/sinopia/_search", (req, res) => {
// Only use the method, path, and body from the original request: method and
// path have already been validated above and the body must be a
// JSON-serializeable entity

let searchUri = `${Config.indexUrl}/${req.params.index}/sinopia/_search`
if (!_.isEmpty(req.query)) {
const originalUrl = `${req.protocol}://${req.hostname}${req.originalUrl}`
searchUri += new URL(originalUrl).search
}

request({
method: req.method,
uri: searchUri,
body: req.body,
json: true,
app.use(
"/api/search",
proxy(Config.indexUrl, {
parseReqBody: false,
proxyReqOptDecorator(proxyReqOpts) {
delete proxyReqOpts.headers.origin
return proxyReqOpts
},
filter: (req) => req.method === "POST",
})
.on("error", (err) => {
console.error(`error making request to ElasticSearch: ${err}`)
res.status(500).json({
error: "server error: could not make request to ElasticSearch",
})
})
.pipe(res)
.on("error", (err) => {
console.error(`error returning ElasticSearch response: ${err}`)
res
.status(500)
.json({ error: "server error: could not send ElasticSearch response" })
})
})
)

app.get("/", (req, res) => {
res.sendFile(`${__dirname}/dist/index.html`)
Expand Down

0 comments on commit 4c61881

Please sign in to comment.