I am setting up a local proxy to redirect specific URLs to another server, I am running my expressJS server as my main server, I have another server running on a different port... My express JS config is as follows
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 8080;
const API_URL = "<http://localhost:8989>";
app.get("/status", (req, res, next) => {
res.send('This is a proxy service');
});
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/dist/index.html'));
});
app.use(express.static('dist'))
const proxyOptions = {
target: API_URL,
changeOrigin: true
}
const proxy = createProxyMiddleware(proxyOptions);
app.use('/?access', proxy)
app.listen(PORT, () => {
console.log(`Proxy Started at http://localhost:${PORT}`)
});
I want any URL starting with /?access
to redirect to the other server localhost:8989
BUT keep the /?access...
intact so it can submit that information to the new server. Can anyone see what I am doing wrong?
I am using FETCH to send the information I need
fetch('/?access=myAccessToken&action=off')
it is also worth noting that I get 304 in the browser console.
I managed to configure app.use('/?access', proxy)
as per ExpressJS docs, and have also also consulted the http-proxy-middleware documentation and, tried a quick Google to help resolve the issue, but nothing was helpful...
I have tried adding the URL to a standard link (a href) and I still get the same issue.
<a href="/?access=myAccessToken&action=off">Click Me</a>
Edit: for clarity.
When you write:
app.use('/?access'
the ?
in the url will tell express to match the route
/access
It is not the literal ?
.
But in your front-end code you are using it to mean query parameter so your link:
<a href="/?access=myAccessToken&action=off">Click Me</a>
Is going to be routed to the /
path with a query parameter key of access
. It will therefore just be picked up by the /
route handler on port 8080
and not proxied. For example:
http://localhost:8080/?access=myAccessToken&action=off
I think what would help you achieve the desired outcome would be to have your route to proxy be something simple like /auth
which would then look like:
app.use('/auth', proxy)
Now when you navigate to:
<a href="/auth?access=myAccessToken&action=off">Click Me</a>
The request will be proxied to:
http://localhost:8989/auth?access=myAccessToken&action=off