How to proxy particular host using http-proxy-middleware? - javascript

I am using http-proxy-middleware to proxy hosts in my React project.
Below is the code from setupProxy.js file:
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = function(app) {
app.use('/api', createProxyMiddleware({ target: 'http://localhost:8080', changeOrigin: true, }));
app.use('/api/user/logout', createProxyMiddleware({ target: 'http://localhost:9091', changeOrigin: true, }))
};
As you can see I added two proxy codes. For the logout, I want to use a different host. /api is working fine, but the /api/user/logout is not working.
Thanks in advance.

Because when the request goes to '/api/user/logout'.
app.use('/api') finds '/api' in the url and it fits the condition of the first app.use
You need to use regExp
app.use(/\/api\/?$/, createProxyMiddleware())

Related

Error React Proxy error: Could not proxy request

Why do I got this error:
Proxy error: Could not proxy request /api/v1/management/me from localhost:3000 to http://localhost:8080 (ECONNREFUSED).
Got this axios setting:
axios.defaults.baseURL = "http://localhost:3000/";
And set this in package.json:
"proxy": "http://localhost:8080"
tried also:
"proxy": "http://localhost:8080/"
And have following call:
axios({
method: "get",
url: "api/v1/management/me",
data: {},
headers: { crossDomain: true },
})
When I call directly http://localhost:8080/api/v1/management/me I got response from server.
I have following backend, Vapor route setting. Maybe something wrong / specific here?
let protectedAPIRouter = authSessionRouter.grouped("api/v1").grouped(User.guardAuthMiddleware())
let managementAPIRouter = protectedAPIRouter.grouped("management")
I would suggest the following solutions:
Try to change localhost to IP address: "proxy": "http://your_IP_address:8080"
Try this construction also:
"proxy": {
"/api/*": {
"target": "http://localhost:8080",
"secure": false
}
}
You need to set up a proxy to the backend service you want to access.
First install (http-proxy-middleware) package.
Remove the ("proxy": "http://localhost:8080/") or the Url behind the proxy in the package json file.
In the src folder create a file (setupProxy.js) and and the following code.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8080',
changeOrigin: true,
})
);
};
I solved this issue change localhost to 127.0.0.1 in the package.json over the client project.

Zero response through http-proxy-middleware

I am trying to debug a proxy in Express, using http-proxy-middleware, but no matter what I do I get absolutely zero response. The endpoint sends the response but it is never returned by the proxy and the onProxyRes event is never triggered. Also the endpoint can be accessed directly through curl, Insomnia, fetch API and request-promise and is in use as an API for our customers.
Even with a setup as simple as:
app.use('/api', proxy({
target: 'https://my.secret.endpoint',
changeOrigin: true
});
I get absolutely zero response, except for a ECONNRESET after timeout. Any suggestions?
Heureka! I found the answer I was looking for! The offending party was (in my case) the express.urlencoded() middleware, which does some trickery that ultimately messes up the proxy. This can be resolved by applying the offending middleware after the proxy. Other middleware that might do this include cookie-parserand bodyParser (both of which are deprecated).
More on the issue here: https://github.com/chimurai/http-proxy-middleware/issues/40
Another solution for anyone coming here with the same issue but did not solve it.
In proxy configuration make sure you are matching any path
with double ** not only *
const proxy = require("http-proxy-middleware");
module.exports = function(app) {
app.use(proxy("/api/**", { // https://github.com/chimurai/http-proxy-middleware
target: "http://localhost:5000",
secure: false
}));
};
For more check this reference
ViggoV
You need to disable the SSL when the target is https.
Like as this:
app.use('/api', proxy({
target: 'https://my.secret.endpoint',
changeOrigin: true,
secure: false
});

cannot GET error 404 on reload?

my react router is working fine with dev env, this is what I did in webpack dev server:
historyApiFallback: {
index: 'index.html',
}
so in production mode I wanted to do the same, I did it in express like this:
const indexPath = path.join(__dirname, '../public/index.html')
const publicPath = express.static(path.join(__dirname, '../public'))
app.use('/public', publicPath)
app.use('/graphql', graphQLHTTP(async (req) => {
let { user } = await getUser(req.headers.authorization);
if(!user) {
user = 'guest'
}
return {
schema,
pretty: true,
graphiql: true,
context: {
user,
}
}
}));
app.get('/', function (_, res) { res.sendFile(indexPath) });
I did not change anything with react-router-dom so I am am assuming the error is in my express config. so what's the equivalent of historyApiFallback in production mode? below is my webpack bundle config:
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js',
publicPath: '/public/'
},
in my html I reference the bundle like this:
<script type="text/javascript" src="/public/bundle.js"></script>
I think a have the right config but when I reload I get cannot GET Error 404?
You should add this line to your app:
app.get('*', function (_, res) { res.sendFile(indexPath) });
Or you should use this package better: https://github.com/bripkens/connect-history-api-fallback
You should read more about history mode:
To get rid of the hash, we can use the router's history mode, which leverages the history.pushState API to achieve URL navigation without a page reload:
When using history mode, the URL will look "normal," e.g. http://oursite.com/user/id. Beautiful!
Here comes a problem, though: Since our app is a single page client-side app, without a proper server configuration, the users will get a 404 error if they access http://oursite.com/user/id directly in their browser. Now that's ugly.
Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!

Rewriting Webpack Proxy URLs

I'm using Webpack Dev Server to proxy my files from an external url, that's because I'm using it to develop locally and proxying the PHP/Twig files from the server, so that way I don't need to set up all the back-end locally.
But the problem is that I need to rewrite the assets urls to pull these files from my local machine, not from the proxy. Right now, when I open my localhost, all the assets are being loaded from the server. i.e: http://mycoolwebsite.com/core/somefolder/assets/styles.css
And I need to replace that to pull from my localhost, like this:
/assets/styles.css
This is what I have now:
devServer: {
compress: true,
port: 9000,
proxy: {
'*': {
target: 'http://mycoolwebsite.com',
changeOrigin: true,
secure: false
}
}
Any clue?
Thanks!
you want all request that go to your server "http://mycoolwebsite.com/**"
to go to your local machine: "http://localhost:9000/" (assuming its running on port 9000)
so try this:
proxy: {
'/assets/**': {
target: 'http://localhost:9000',
secure: false,
pathRewrite: function(req, path) {
//use the pathRewrite to modify your path if needed
return path;
}
}
now it shouldn't make any difference what server you are actually calling. every request that includes '/assets/' should go to your localhost. (I can not test it atm)

restangular remove and put error net::ERR_NAME_NOT_RESOLVED

i have this error when i try to do a put or a remove with restangular the post and the getList() works perfectly,
when i'm going to edit mi object i create a object like this
edited = Restangular.copy(danger);
danger is my modelobject from my template in a table i just grab the object from the table, the object is fine.
then in my function i just try to do
edited.put();
and the error is OPTIONS http://dangers/1/ net::ERR_NAME_NOT_RESOLVED
like restangular is not generating the url, the post url is http://localhost:8000/dangers/
i'm using gulp with a proxy in the dev enviroment to capture the api requests
gulp.task('server', ['build'], function() {
gulp.src('./build')
.pipe($.webserver({
port: 8080,
host: 'localhost',
fallback: 'index.html',
livereload: {
enable: true,
port: 8181
},
open: true,
// django app
proxies: [{
source: '/api',
target: 'http://localhost:8000/api'
}]
}));
});
This was my error django restframework needs the trailing slash in every url the solution was to add in the config of restangular
RestangularProvider.setRequestSuffix('/');

Categories